<template>
  <div class="app-container">
    <!-- 顶部操作栏 -->
    <div class="header-section">
      <el-row :gutter="20" type="flex" align="middle">
        <el-col :span="8">
          <el-select
            v-model="selectedTemplateId"
            placeholder="选择日程模板"
            style="width: 100%;"
            @change="handleTemplateChange"
          >
            <el-option
              v-for="template in templateList"
              :key="template.id"
              :label="template.name"
              :value="template.id"
            />
          </el-select>
        </el-col>
        <el-col :span="16">
          <div class="header-actions">
            <el-button
              type="primary"
              icon="el-icon-plus"
              :disabled="!selectedTemplateId"
              title="新建记录"
              @click="showCreateRecord"
            />
            <el-button
              type="primary"
              icon="el-icon-setting"
              title="设置模板"
              @click="showTemplateDialog = true"
            />
            <el-button
              type="success"
              icon="el-icon-timer"
              :disabled="!selectedTemplateId"
              title="一键分配日程"
              @click="autoScheduleAllProjects"
            />
            <el-button
              type="warning"
              icon="el-icon-s-operation"
              title="管理项目状态"
              @click="showProjectStatusDialog = true"
            />
            <el-button
              icon="el-icon-refresh"
              title="刷新"
              @click="refreshRecords"
            />
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 日程记录列表 -->
    <div v-if="selectedTemplateId" class="records-section">
      <!-- 统计信息栏 -->
      <div class="stats-info" style="margin-bottom: 15px; padding: 10px; background: #f0f9ff; border-radius: 4px;">
        <el-row :gutter="20">
          <el-col :span="8">
            <div style="display: flex; align-items: center;">
              <i class="el-icon-data-line" style="color: #409EFF; margin-right: 5px;" />
              <span>日程总数：<strong style="color: #409EFF;">{{ recordList.length }}</strong> 条</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div style="display: flex; align-items: center;">
              <i class="el-icon-office-building" style="color: #67C23A; margin-right: 5px;" />
              <span>涉及项目：<strong style="color: #67C23A;">{{ getUniqueProjectsInRecords() }}</strong> 个</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div v-if="lastAutoScheduleDate" style="display: flex; align-items: center;">
              <i class="el-icon-timer" style="color: #E6A23C; margin-right: 5px;" />
              <span>上次分配：<strong style="color: #E6A23C;">{{ formatLastScheduleDate(lastAutoScheduleDate) }}</strong></span>
            </div>
          </el-col>
        </el-row>
      </div>
      <!-- 视图切换栏 -->
      <div class="view-switcher">
        <el-radio-group v-model="viewMode" @change="handleViewModeChange">
          <el-radio-button label="table" title="表格视图">
            <i class="el-icon-s-grid" />
          </el-radio-button>
          <el-radio-button label="timeline" title="时间线视图">
            <i class="el-icon-time" />
          </el-radio-button>
        </el-radio-group>
      </div>

      <!-- 批量操作栏 -->
      <div v-if="selectedRecords.length > 0 && viewMode === 'table'" class="batch-actions">
        <div class="batch-info">
          <span>已选择 {{ selectedRecords.length }} 项</span>
        </div>
        <div class="batch-buttons">
          <el-button
            type="success"
            size="small"
            icon="el-icon-check"
            :disabled="selectedRecords.length === 0"
            title="批量标记完成"
            @click="batchCompleteRecords"
          />
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            :disabled="selectedRecords.length === 0"
            title="批量删除"
            @click="batchDeleteRecords"
          />
        </div>
      </div>

      <!-- 表格视图 -->
      <div v-if="viewMode === 'table'">
        <!-- 拖拽使用提示 -->
        <div v-if="recordList.length > 1" class="drag-tip">
          <i class="el-icon-info" /> 提示：可以拖拽左侧的 <i class="el-icon-s-operation" /> 图标来交换两个记录的时间，方便快速调整顺序
        </div>

        <el-table
          v-loading="recordLoading"
          :data="recordList"
          style="width: 100%"
          :row-style="getRowStyle"
          :row-class-name="getRowClassName"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />

          <!-- 拖拽把手列 -->
          <el-table-column label="拖拽" width="60" align="center">
            <template slot-scope="scope">
              <div
                class="drag-handle"
                draggable="true"
                :title="'拖拽交换时间：' + scope.row.project_name"
                @dragstart="handleDragStart(scope.row, $event)"
                @dragover="handleDragOver"
                @dragenter="handleDragEnter"
                @dragend="handleDragEnd"
                @drop="handleDrop(scope.row, $event)"
              >
                <i class="el-icon-s-operation" />
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="project_name" label="公司" width="150" />
          <el-table-column label="阶段" width="100">
            <template slot-scope="scope">
              {{ (scope.row.schedule && scope.row.schedule.stage) || scope.row.schedule_stage || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="计划时间" width="250">
            <template slot-scope="scope">
              <div>
                <div style="display: flex; align-items: center; margin-bottom: 5px;">
                  <el-date-picker
                    v-model="scope.row.schedule_time"
                    type="datetime"
                    format="yyyy-MM-dd HH:mm"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    size="small"
                    style="flex: 1;"
                    @change="updateRecordTime(scope.row)"
                  />
                  <el-tag
                    v-if="checkTimeConflict(scope.row)"
                    type="danger"
                    size="mini"
                    style="margin-left: 8px;"
                  >
                    <i class="el-icon-warning" /> 冲突
                  </el-tag>
                </div>

                <!-- 时间间隔提示 -->
                <div style="display: flex; justify-content: space-between; font-size: 11px; color: #909399; margin-top: 2px; padding: 0 2px;">
                  <!-- 上次完成的时间间隔 -->
                  <el-tooltip
                    v-if="getLastCompletedInfo(scope.row.project_id)"
                    :content="`上次完成: ${getLastCompletedInfo(scope.row.project_id).fullTitle} (${getLastCompletedInfo(scope.row.project_id).date})`"
                    placement="top"
                  >
                    <span :style="{ color: '#E6A23C', cursor: 'help' }">
                      <i class="el-icon-finished" style="font-size: 10px;" />
                      {{ getTimeIntervalFromLastCompleted(scope.row.project_id) }}
                    </span>
                  </el-tooltip>
                  <span v-else style="opacity: 0.5;">暂无完成记录</span>

                  <!-- 距离当前时间 -->
                  <span :style="{ color: getTimeFromNow(scope.row.schedule_time).includes('前') ? '#F56C6C' : '#67C23A' }">
                    <i class="el-icon-time" style="font-size: 10px;" />
                    {{ getTimeFromNow(scope.row.schedule_time) || '时间待定' }}
                  </span>
                </div>

                <!-- 建议时间 -->
                <div v-if="checkTimeConflict(scope.row)" class="time-suggestions">
                  <div style="font-size: 12px; color: #606266; margin-bottom: 3px;">建议时间:</div>
                  <div class="suggestion-buttons">
                    <el-button
                      v-for="suggestion in getSuggestedTime(scope.row)"
                      :key="suggestion.time"
                      size="mini"
                      type="success"
                      plain
                      style="margin-right: 5px; margin-bottom: 2px;"
                      @click="applySuggestedTime(scope.row, suggestion.datetime)"
                    >
                      {{ suggestion.time }}
                    </el-button>
                    <span v-if="getSuggestedTime(scope.row).length === 0" style="font-size: 12px; color: #999;">
                      当日时间段已满
                    </span>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="通知状态" width="120">
            <template slot-scope="scope">
              <el-tag
                :type="scope.row && scope.row.send_notice ? 'success' : 'info'"
                size="small"
              >
                <i :class="scope.row && scope.row.send_notice ? 'el-icon-check' : 'el-icon-message'" />
                {{ scope.row && scope.row.send_notice ? '已通知' : '未通知' }}
              </el-tag>
            </template>
          </el-table-column>

          <!-- 历史日程列 -->
          <el-table-column label="历史日程" width="200">
            <template slot-scope="scope">
              <div v-if="getProjectCompletedRecords(scope.row.project_id).length > 0" class="history-records">
                <el-popover
                  placement="bottom"
                  width="450"
                  trigger="click"
                >
                  <div class="history-list">
                    <!-- 项目标题（固定在顶部） -->
                    <div style="padding: 10px; background: #f5f7fa; border-bottom: 2px solid #e4e7ed; margin-bottom: 8px; position: sticky; top: 0; z-index: 10;">
                      <h4 style="margin: 0; color: #303133; font-size: 14px; font-weight: bold;">
                        <i class="el-icon-folder-opened" style="margin-right: 5px; color: #409eff;" />
                        {{ scope.row.project_name }}
                      </h4>
                      <p style="margin: 4px 0 0 0; font-size: 12px; color: #909399;">
                        历史完成记录 ({{ getProjectCompletedRecords(scope.row.project_id).length }} 条)
                      </p>
                    </div>

                    <!-- 历史记录列表容器（可滚动） -->
                    <div style="max-height: 300px; overflow-y: auto; overflow-x: hidden;">
                      <div
                        v-for="(record, index) in getProjectCompletedRecords(scope.row.project_id)"
                        :key="record.id"
                        class="history-item"
                        style="padding: 8px; border-bottom: 1px solid #eee;"
                      >
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                          <div style="flex: 1;">
                            <div style="font-size: 12px; color: #999; margin-bottom: 2px;">
                              <i class="el-icon-time" style="margin-right: 3px;" />
                              {{ formatDate(record.schedule_time) }}
                            </div>
                            <div style="font-size: 14px; margin: 2px 0; color: #303133; font-weight: 500;">
                              <i class="el-icon-document" style="margin-right: 3px; color: #409eff;" />
                              {{ record.schedule_title || (record.schedule && record.schedule.title) || '未命名日程' }}
                            </div>
                            <div style="font-size: 13px; margin: 2px 0; color: #606266;">
                              <strong>阶段:</strong> {{ record.schedule_stage || '-' }}
                            </div>
                            <div v-if="record.complete_content" style="font-size: 12px; color: #666; margin-top: 4px; padding: 4px 8px; background: #f9f9f9; border-radius: 4px;">
                              <i class="el-icon-chat-dot-round" style="margin-right: 3px;" />
                              {{ record.complete_content }}
                            </div>
                          </div>
                          <el-button
                            type="danger"
                            size="mini"
                            icon="el-icon-delete"
                            circle
                            title="删除历史记录"
                            @click.stop="deleteCompletedRecord(record)"
                          />
                        </div>
                      </div>
                    </div>
                  </div>
                  <el-tag slot="reference" type="success" size="small" style="cursor: pointer;">
                    <i class="el-icon-time" />
                    已完成 {{ getProjectCompletedRecords(scope.row.project_id).length }} 条
                  </el-tag>
                </el-popover>
              </div>
              <span v-else style="color: #999; font-size: 12px;">暂无历史</span>
            </template>
          </el-table-column>
          <el-table-column label="固定时间" width="150">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.is_time_fixed"
                active-color="#67c23a"
                inactive-color="#dcdfe6"
                active-text="固定"
                inactive-text="灵活"
                @change="toggleTimeFixed(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="优先级" width="100">
            <template slot-scope="scope">
              <el-tag
                :type="getPriorityType((scope.row.schedule && scope.row.schedule.priority) || scope.row.schedule_priority)"
                size="small"
              >
                {{ getPriorityText((scope.row.schedule && scope.row.schedule.priority) || scope.row.schedule_priority) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="note" label="备注" show-overflow-tooltip />

          <el-table-column prop="user_name" label="负责人" width="120" />
          <el-table-column label="状态" width="100">
            <template slot-scope="scope">
              <el-tag
                :type="scope.row.is_done ? 'success' : 'warning'"
                size="small"
              >
                {{ scope.row.is_done ? '已完成' : '进行中' }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="350" fixed="right">
            <template slot-scope="scope">
              <el-button
                v-if="!scope.row.is_done"
                type="success"
                size="mini"
                icon="el-icon-check"
                title="标记完成"
                @click="completeRecord(scope.row)"
              />
              <el-button
                :type="scope.row && scope.row.send_notice ? 'info' : 'warning'"
                size="mini"
                :icon="scope.row && scope.row.send_notice ? 'el-icon-refresh' : 'el-icon-message'"
                :title="scope.row && scope.row.send_notice ? '重新通知' : '钉钉通知'"
                @click="sendDingTalkNotification(scope.row)"
              />
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                title="编辑"
                @click="editRecord(scope.row)"
              />
              <el-button
                type="info"
                size="mini"
                icon="el-icon-setting"
                title="设置日程"
                @click="editSchedule(scope.row)"
              />
              <el-button
                type="success"
                size="mini"
                plain
                icon="el-icon-plus"
                title="添加到系统提醒事项"
                @click="addToSystemReminder(scope.row)"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 时间线视图 -->
      <div v-if="viewMode === 'timeline'" v-loading="recordLoading" class="timeline-view">
        <div v-if="groupedRecords.length === 0" class="no-data">
          <el-empty description="暂无日程记录" />
        </div>

        <div v-for="dateGroup in groupedRecords" :key="dateGroup.date" class="date-group">
          <div class="date-header">
            <h3>{{ formatDateHeader(dateGroup.date) }}</h3>
            <span class="record-count">{{ dateGroup.records.length }} 个会议</span>
          </div>

          <el-timeline>
            <el-timeline-item
              v-for="record in dateGroup.records"
              :key="record.id"
              :timestamp="formatTimeOnly(record.schedule_time)"
              placement="top"
              :type="getTimelineItemType(record)"
              :color="getTimelineItemColor(record)"
              :size="getTimelineItemSize(record)"
            >
              <el-card class="timeline-card" :class="getCardClass(record)">
                <div class="timeline-card-header">
                  <div class="header-top">
                    <div class="company-title">
                      <span class="company-name">{{ record.project_name }}</span>
                      <span class="divider">·</span>
                      <span class="schedule-title">
                        <i :class="getScheduleIcon(record)" />
                        {{ (record.schedule && record.schedule.title) || record.schedule_title || '未设置' }}
                      </span>
                      <el-tag
                        v-if="checkTimeConflict(record)"
                        type="danger"
                        size="mini"
                        style="margin-left: 8px;"
                      >
                        <i class="el-icon-warning" /> 冲突
                      </el-tag>
                      <el-tag
                        v-if="record.is_time_fixed"
                        type="success"
                        size="mini"
                        style="margin-left: 8px;"
                      >
                        <i class="el-icon-lock" /> 固定
                      </el-tag>
                    </div>
                    <div class="card-actions">
                      <el-button-group size="mini">
                        <el-button
                          v-if="!record.is_done"
                          type="success"
                          icon="el-icon-check"
                          title="完成"
                          @click="completeRecord(record)"
                        />
                        <el-button
                          :type="record && record.send_notice ? 'info' : 'warning'"
                          :icon="record && record.send_notice ? 'el-icon-refresh' : 'el-icon-message'"
                          :title="record && record.send_notice ? '重新发送通知' : '发送钉钉通知'"
                          @click="sendDingTalkNotification(record)"
                        />
                        <el-button
                          type="primary"
                          icon="el-icon-edit"
                          title="编辑"
                          @click="editRecord(record)"
                        />
                        <el-button
                          type="info"
                          icon="el-icon-setting"
                          title="设置日程"
                          @click="editSchedule(record)"
                        />
                      </el-button-group>
                      <el-button
                        size="mini"
                        type="success"
                        plain
                        icon="el-icon-plus"
                        title="添加到系统提醒事项"
                        style="margin-left: 8px;"
                        @click="addToSystemReminder(record)"
                      />
                    </div>
                  </div>
                </div>

                <div class="timeline-card-content">
                  <div class="content-row">
                    <span class="label">负责人：</span>
                    <span class="value">{{ record.user_name }}</span>
                    <span class="label stage-label">阶段：</span>
                    <span class="value">{{ (record.schedule && record.schedule.stage) || record.schedule_stage || '-' }}</span>
                  </div>
                  <div class="content-row">
                    <span class="label">订单状态：</span>
                    <el-select
                      v-if="projectOrderStates[record.project_id]"
                      v-model="projectOrderStates[record.project_id].current_state_id"
                      placeholder="选择状态"
                      size="mini"
                      clearable
                      style="width: 150px;"
                      @change="updateProjectOrderState(record.project_id)"
                    >
                      <el-option
                        v-for="state in projectOrderStates[record.project_id].available_states"
                        :key="state.id"
                        :label="state.name"
                        :value="state.id"
                      >
                        <span style="display: flex; align-items: center;">
                          <span
                            :style="{backgroundColor: state.color, width: '10px', height: '10px', borderRadius: '50%', marginRight: '5px'}"
                          />
                          {{ state.name }}
                        </span>
                      </el-option>
                    </el-select>
                    <span v-else style="color: #999; font-size: 12px;">加载中...</span>
                  </div>
                  <div class="content-row">
                    <span class="label">优先级：</span>
                    <el-tag
                      :type="getPriorityType((record.schedule && record.schedule.priority) || record.schedule_priority)"
                      size="small"
                    >
                      {{ getPriorityText((record.schedule && record.schedule.priority) || record.schedule_priority) }}
                    </el-tag>
                    <span class="label status-label">状态：</span>
                    <el-tag
                      :type="record.is_done ? 'success' : 'warning'"
                      size="small"
                    >
                      {{ record.is_done ? '已完成' : '进行中' }}
                    </el-tag>
                  </div>
                  <div class="content-row">
                    <span class="label">通知状态：</span>
                    <el-tag
                      :type="record && record.send_notice ? 'success' : 'info'"
                      size="small"
                    >
                      <i :class="record && record.send_notice ? 'el-icon-check' : 'el-icon-message'" />
                      {{ record && record.send_notice ? '已通知' : '未通知' }}
                    </el-tag>
                  </div>
                  <div class="content-row">
                    <span class="label">时间设置：</span>
                    <el-switch
                      v-model="record.is_time_fixed"
                      active-color="#67c23a"
                      inactive-color="#dcdfe6"
                      active-text="固定"
                      inactive-text="灵活"
                      size="small"
                      @change="toggleTimeFixed(record)"
                    />
                  </div>
                  <div v-if="record.note" class="content-row note-row">
                    <span class="label">备注：</span>
                    <span class="value">{{ record.note }}</span>
                  </div>
                </div>

                <!-- 冲突建议时间 -->
                <div v-if="checkTimeConflict(record)" class="conflict-suggestions">
                  <div class="suggestions-header">建议时间:</div>
                  <div class="suggestion-buttons">
                    <el-button
                      v-for="suggestion in getSuggestedTime(record)"
                      :key="suggestion.time"
                      size="mini"
                      type="success"
                      plain
                      @click="applySuggestedTime(record, suggestion.datetime)"
                    >
                      {{ suggestion.time }}
                    </el-button>
                    <span v-if="getSuggestedTime(record).length === 0" class="no-suggestions">
                      当日时间段已满
                    </span>
                  </div>
                </div>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>

      <!-- AI重新规划按钮 -->
      <div v-if="selectedTemplateId && recordList.length > 0" class="ai-reschedule-section">
        <el-button
          type="primary"
          icon="el-icon-cpu"
          :disabled="!selectedTemplateId"
          title="AI重新规划时间"
          @click="showAIRescheduleConfirm"
        />
        <div style="font-size: 12px; color: #999; margin-top: 5px;">
          AI将智能重新安排当前模板下所有未完成记录的会议时间
        </div>
      </div>

      <!-- 分页 -->
      <el-pagination
        v-show="total > 0"
        background
        :current-page="listQuery.page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="listQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 模板设置对话框 -->
    <el-dialog
      title="模板设置"
      :visible.sync="showTemplateDialog"
      width="80%"
      @close="resetTemplateForm"
    >
      <div class="template-tabs">
        <el-tabs v-model="activeTab">
          <!-- 模板列表 -->
          <el-tab-pane label="模板管理" name="list">
            <div class="template-actions">
              <el-button
                type="primary"
                icon="el-icon-plus"
                title="新建模板"
                @click="showCreateTemplate"
              />
            </div>

            <el-table :data="templateList" style="width: 100%; margin-top: 20px;">
              <el-table-column prop="name" label="模板名称" width="150" />
              <el-table-column prop="title" label="日程标题" width="150" />
              <el-table-column prop="schedule_type" label="类型" width="80" />
              <el-table-column prop="priority" label="优先级" width="80" />
              <el-table-column label="适用项目" width="200">
                <template slot-scope="scope">
                  <span v-if="!scope.row.applicable_projects_names || scope.row.applicable_projects_names.length === 0" style="color: #999;">
                    全部项目
                  </span>
                  <template v-else>
                    <el-tag
                      v-for="projectName in scope.row.applicable_projects_names"
                      :key="projectName"
                      size="mini"
                      style="margin-right: 5px;"
                    >
                      {{ projectName }}
                    </el-tag>
                  </template>
                </template>
              </el-table-column>
              <el-table-column label="状态" width="80">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.is_active ? 'success' : 'danger'" size="small">
                    {{ scope.row.is_active ? '启用' : '禁用' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100" fixed="right">
                <template slot-scope="scope">
                  <el-button
                    type="primary"
                    size="mini"
                    icon="el-icon-edit"
                    title="编辑"
                    @click="editTemplate(scope.row)"
                  />
                  <el-button
                    type="danger"
                    size="mini"
                    icon="el-icon-delete"
                    title="删除"
                    @click="deleteTemplate(scope.row)"
                  />
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <!-- 创建/编辑模板 -->
          <el-tab-pane label="模板编辑" name="edit">
            <el-form ref="templateForm" :model="templateForm" :rules="templateRules" label-width="120px">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="模板名称" prop="name">
                    <el-input v-model="templateForm.name" placeholder="请输入模板名称" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="日程标题" prop="title">
                    <el-input v-model="templateForm.title" placeholder="请输入日程标题" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="日程内容" prop="content">
                <el-input
                  v-model="templateForm.content"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入日程内容描述"
                />
              </el-form-item>

              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="日程类型" prop="schedule_type">
                    <el-select v-model="templateForm.schedule_type" style="width: 100%;">
                      <el-option label="会议" value="meeting" />
                      <el-option label="任务" value="task" />
                      <el-option label="里程碑" value="milestone" />
                      <el-option label="评审" value="review" />
                      <el-option label="其他" value="other" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="优先级" prop="priority">
                    <el-select v-model="templateForm.priority" style="width: 100%;">
                      <el-option label="低" value="low" />
                      <el-option label="普通" value="normal" />
                      <el-option label="高" value="high" />
                      <el-option label="紧急" value="urgent" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="阶段" prop="stage">
                    <el-input v-model="templateForm.stage" placeholder="如: s1, s2等" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="是否重复">
                <el-switch v-model="templateForm.is_repeat" />
              </el-form-item>

              <div v-if="templateForm.is_repeat">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="重复类型">
                      <el-select v-model="templateForm.repeat_type" style="width: 100%;">
                        <el-option label="每日" value="daily" />
                        <el-option label="每周" value="weekly" />
                        <el-option label="每月" value="monthly" />
                        <el-option label="每年" value="yearly" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="重复间隔">
                      <el-input-number v-model="templateForm.repeat_interval" :min="1" style="width: 100%;" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>

              <el-form-item label="默认时长(小时)">
                <el-input-number
                  v-model="templateForm.default_duration_hours"
                  :min="0"
                  :step="0.5"
                  style="width: 200px;"
                  placeholder="可选，不填则无默认时长"
                  clearable
                />
                <div style="font-size: 12px; color: #999; margin-top: 5px;">
                  可选填，不填则无默认时长限制
                </div>
              </el-form-item>

              <el-form-item label="是否启用">
                <el-switch v-model="templateForm.is_active" />
              </el-form-item>

              <el-form-item label="适用项目">
                <el-select
                  v-model="templateForm.applicable_project_ids"
                  multiple
                  placeholder="选择适用项目（留空表示适用于所有项目）"
                  style="width: 100%;"
                >
                  <el-option
                    v-for="project in projectList"
                    :key="project.id"
                    :label="project.name"
                    :value="project.id"
                  />
                </el-select>
                <div style="font-size: 12px; color: #999; margin-top: 5px;">
                  留空表示适用于所有项目
                </div>
              </el-form-item>
            </el-form>

            <div class="form-actions">
              <el-button @click="resetTemplateForm">取消</el-button>
              <el-button type="primary" @click="saveTemplate">保存模板</el-button>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>

    <!-- 编辑记录对话框 -->
    <el-dialog
      title="编辑日程记录"
      :visible.sync="showEditDialog"
      width="500px"
    >
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="计划时间">
          <el-date-picker
            v-model="editForm.schedule_time"
            type="datetime"
            format="yyyy-MM-dd HH:mm"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select
            v-if="editForm.project_id && projectOrderStates[editForm.project_id]"
            v-model="projectOrderStates[editForm.project_id].current_state_id"
            placeholder="选择状态"
            clearable
            style="width: 100%;"
            @change="updateProjectOrderState(editForm.project_id)"
          >
            <el-option
              v-for="state in projectOrderStates[editForm.project_id].available_states"
              :key="state.id"
              :label="state.name"
              :value="state.id"
            >
              <span style="display: flex; align-items: center;">
                <span
                  :style="{backgroundColor: state.color, width: '12px', height: '12px', borderRadius: '50%', marginRight: '8px'}"
                />
                {{ state.name }}
              </span>
            </el-option>
          </el-select>
          <div v-else style="color: #999; font-size: 12px;">加载状态中...</div>
        </el-form-item>
        <el-form-item label="时间设置">
          <el-switch
            v-model="editForm.is_time_fixed"
            active-color="#67c23a"
            inactive-color="#dcdfe6"
            active-text="固定时间"
            inactive-text="灵活调整"
          />
          <div style="font-size: 12px; color: #999; margin-top: 5px;">
            固定时间不会被AI重新规划功能修改
          </div>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="editForm.note"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="showEditDialog = false">取 消</el-button>
        <el-button type="primary" @click="saveRecordEdit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 钉钉通知对话框 -->
    <el-dialog
      title="发送钉钉通知"
      :visible.sync="showNotifyDialog"
      width="500px"
    >
      <el-form :model="notifyForm" label-width="100px">
        <el-form-item label="日程信息">
          <div style="background: #f5f7fa; padding: 10px; border-radius: 4px; margin-bottom: 10px;">
            <div style="margin-bottom: 8px;"><strong>公司：</strong>{{ notifyForm.record_info && notifyForm.record_info.project_name }}</div>
            <div style="margin-bottom: 8px;"><strong>标题：</strong>{{ notifyForm.record_info && ((notifyForm.record_info.schedule && notifyForm.record_info.schedule.title) || notifyForm.record_info.schedule_title || '未设置') }}</div>
            <div style="margin-bottom: 8px;"><strong>时间：</strong>{{ notifyForm.record_info && notifyForm.record_info.schedule_time }}</div>
            <div style="margin-bottom: 8px;"><strong>负责人：</strong>{{ notifyForm.record_info && notifyForm.record_info.user_name }}</div>
            <div>
              <strong>通知状态：</strong>
              <el-tag
                :type="notifyForm.record_info && notifyForm.record_info.send_notice ? 'success' : 'info'"
                size="small"
              >
                <i :class="notifyForm.record_info && notifyForm.record_info.send_notice ? 'el-icon-check' : 'el-icon-message'" />
                {{ notifyForm.record_info && notifyForm.record_info.send_notice ? '已通知' : '未通知' }}
              </el-tag>
            </div>
          </div>
          <div v-if="notifyForm.record_info && notifyForm.record_info.send_notice" style="background: #fff7e6; padding: 8px; border-radius: 4px; border: 1px solid #ffe7ba; font-size: 12px; color: #e6a23c; margin-bottom: 10px;">
            <i class="el-icon-warning" /> 此日程已经发送过通知，确定要重新发送吗？
          </div>
        </el-form-item>
        <el-form-item label="自定义消息" required>
          <el-input
            v-model="notifyForm.message"
            type="textarea"
            :rows="4"
            placeholder="请输入要发送的自定义消息内容..."
          />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="showNotifyDialog = false">取 消</el-button>
        <el-button type="primary" @click="confirmSendNotification">
          {{ notifyForm.record_info && notifyForm.record_info.send_notice ? '重新发送' : '发 送' }}
        </el-button>
      </span>
    </el-dialog>

    <!-- 设置日程对话框 -->
    <el-dialog
      title="设置日程参数"
      :visible.sync="showScheduleDialog"
      width="800px"
      @close="resetScheduleForm"
    >
      <el-form ref="scheduleForm" :model="scheduleForm" :rules="scheduleRules" label-width="120px" class="schedule-form">
        <!-- 基本信息显示 -->
        <div class="schedule-info">
          <el-row>
            <el-col :span="12">
              <div><strong>项目：</strong>{{ scheduleForm.project_name }}</div>
            </el-col>
            <el-col :span="12">
              <div><strong>模板：</strong>{{ scheduleForm.template_name }}</div>
            </el-col>
          </el-row>
        </div>

        <!-- 自定义覆盖设置 -->
        <el-divider content-position="left">自定义设置</el-divider>

        <el-form-item label="自定义标题">
          <el-input
            v-model="scheduleForm.custom_title"
            placeholder="留空则使用模板标题"
            clearable
          />
          <div style="font-size: 12px; color: #999; margin-top: 5px;">
            留空则使用模板标题：{{ scheduleForm.template_title }}
          </div>
        </el-form-item>

        <el-form-item label="自定义内容">
          <el-input
            v-model="scheduleForm.custom_content"
            type="textarea"
            :rows="3"
            placeholder="留空则使用模板内容"
            clearable
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="自定义阶段">
              <el-input
                v-model="scheduleForm.custom_stage"
                placeholder="留空则使用模板阶段"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="自定义优先级">
              <el-select
                v-model="scheduleForm.custom_priority"
                placeholder="留空则使用模板优先级"
                clearable
                style="width: 100%;"
              >
                <el-option label="低" value="low" />
                <el-option label="普通" value="normal" />
                <el-option label="高" value="high" />
                <el-option label="紧急" value="urgent" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 固定时间设置 -->
        <el-divider content-position="left">固定时间设置</el-divider>

        <el-form-item label="使用固定时间">
          <el-switch v-model="scheduleForm.use_fixed_time" />
          <div style="font-size: 12px; color: #999; margin-top: 5px;">
            启用后，自动安排日程时将优先考虑此固定时间
          </div>
        </el-form-item>

        <div v-if="scheduleForm.use_fixed_time">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="固定星期" label-width="80px">
                <el-select v-model="scheduleForm.fixed_weekday" placeholder="选择星期几" style="width: 100%;">
                  <el-option label="周日" :value="0" />
                  <el-option label="周一" :value="1" />
                  <el-option label="周二" :value="2" />
                  <el-option label="周三" :value="3" />
                  <el-option label="周四" :value="4" />
                  <el-option label="周五" :value="5" />
                  <el-option label="周六" :value="6" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="固定小时" label-width="80px">
                <el-select v-model="scheduleForm.fixed_hour" placeholder="选择小时" style="width: 100%;">
                  <el-option
                    v-for="hour in 24"
                    :key="hour-1"
                    :label="`${String(hour-1).padStart(2, '0')}时`"
                    :value="hour-1"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="固定分钟" label-width="80px">
                <el-select v-model="scheduleForm.fixed_minute" placeholder="选择分钟" style="width: 100%;">
                  <el-option label="00分" :value="0" />
                  <el-option label="15分" :value="15" />
                  <el-option label="30分" :value="30" />
                  <el-option label="45分" :value="45" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <el-form-item label="是否启用">
          <el-switch v-model="scheduleForm.is_active" />
          <div style="font-size: 12px; color: #999; margin-top: 5px;">
            禁用后将不再生成新的日程记录
          </div>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="showScheduleDialog = false">取 消</el-button>
        <el-button type="primary" @click="saveScheduleSettings">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 新建记录对话框 -->
    <el-dialog
      title="新建日程记录"
      :visible.sync="showCreateDialog"
      width="600px"
      @close="resetCreateForm"
    >
      <el-form ref="createForm" :model="createForm" :rules="createRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="选择项目" prop="project_id">
              <el-select v-model="createForm.project_id" placeholder="请选择项目" style="width: 100%;" @change="handleProjectChange">
                <el-option
                  v-for="project in projectList"
                  :key="project.id"
                  :label="project.name"
                  :value="project.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="user_id">
              <el-select v-model="createForm.user_id" placeholder="请选择负责人" style="width: 100%;" :disabled="!createForm.project_id">
                <el-option
                  v-for="user in projectUserList"
                  :key="user.id"
                  :label="user.first_name + user.last_name + '(' + user.username + ')'"
                  :value="user.id"
                />
              </el-select>
              <div v-if="!createForm.project_id" style="font-size: 12px; color: #999; margin-top: 5px;">
                请先选择项目
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="日程标题">
          <el-input
            v-model="createForm.schedule_title"
            placeholder="自动从模板获取"
            disabled
            style="background-color: #f5f7fa;"
          />
          <div style="font-size: 12px; color: #999; margin-top: 5px;">
            标题将自动从所选模板中获取，无法手动修改
          </div>
        </el-form-item>

        <el-form-item label="计划时间" prop="schedule_time">
          <div>
            <el-date-picker
              v-model="createForm.schedule_time"
              type="datetime"
              format="yyyy-MM-dd HH:mm"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="请选择计划时间"
              style="width: 100%; margin-bottom: 10px;"
            />
            <div class="time-shortcuts">
              <el-button
                size="mini"
                type="primary"
                plain
                title="明天 9:00"
                @click="setTomorrowTime"
              >
                明天
              </el-button>
              <el-button
                size="mini"
                type="primary"
                plain
                style="margin-left: 8px;"
                title="后天 9:00"
                @click="setDayAfterTomorrowTime"
              >
                后天
              </el-button>
            </div>
          </div>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="阶段">
              <el-input v-model="createForm.schedule_stage" placeholder="如: s1, s2等" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级">
              <el-select v-model="createForm.schedule_priority" style="width: 100%;">
                <el-option label="低" value="low" />
                <el-option label="普通" value="normal" />
                <el-option label="高" value="high" />
                <el-option label="紧急" value="urgent" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注">
          <el-input
            v-model="createForm.note"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="showCreateDialog = false">取 消</el-button>
        <el-button type="primary" @click="saveCreateRecord">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 一键分配日程对话框 -->
    <el-dialog
      title="一键分配日程"
      :visible.sync="showAutoScheduleDialog"
      width="500px"
    >
      <div class="auto-schedule-content">
        <div class="info-section">
          <h4><i class="el-icon-info" /> 分配说明</h4>
          <ul>
            <li>AI将为当前模板<strong>关联的项目</strong>自动安排会议时间</li>
            <li>优先考虑项目设置的固定时间</li>
            <li>按照优先级和阶段合理分配时间段</li>
            <li v-if="getTemplateProjectsCount() === 0" style="color: #F56C6C;">⚠️ 当前模板未关联任何项目</li>
            <li>避免时间冲突，确保合理间隔</li>
          </ul>
        </div>

        <div class="date-selection-section">
          <h4><i class="el-icon-date" /> 选择开始日期</h4>
          <el-form label-width="120px">
            <el-form-item label="开始日期" required>
              <el-date-picker
                v-model="autoScheduleStartDate"
                type="date"
                placeholder="请选择开始日期"
                format="yyyy年MM月dd日"
                value-format="yyyy-MM-dd"
                :picker-options="datePickerOptions"
                style="width: 100%;"
              />
              <div style="font-size: 12px; color: #999; margin-top: 5px;">
                所有新分配的日程将从此日期开始安排
              </div>
            </el-form-item>
          </el-form>
        </div>

        <div class="info-section">
          <h4><i class="el-icon-data-line" /> 当前统计</h4>
          <p>模板：<strong>{{ getCurrentTemplateName() }}</strong></p>
          <p>关联项目数：<strong style="color: #409EFF;">{{ getTemplateProjectsCount() }}</strong> 个</p>
          <p v-if="lastAutoScheduleDate" style="color: #999;">上次分配时间：{{ formatLastScheduleDate(lastAutoScheduleDate) }}</p>
          <el-alert
            v-if="getTemplateProjectsCount() > 0"
            :title="`将为所有 ${getTemplateProjectsCount()} 个关联项目分配日程`"
            type="info"
            :closable="false"
            style="margin-top: 10px;"
          />
        </div>

        <div class="warning-section">
          <el-alert
            title="注意：此操作将为所有适用项目创建新的日程记录"
            type="warning"
            :closable="false"
            show-icon
          />
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="showAutoScheduleDialog = false">取 消</el-button>
        <el-button type="primary" :disabled="!autoScheduleStartDate" @click="executeAutoSchedule">
          <i class="el-icon-timer" /> 确认分配
        </el-button>
      </span>
    </el-dialog>

    <!-- AI重新规划确认对话框 -->
    <el-dialog
      title="AI重新规划时间确认"
      :visible.sync="showAIRescheduleDialog"
      width="600px"
    >
      <div class="ai-reschedule-info">
        <div class="info-section">
          <h4><i class="el-icon-info" /> 重新规划说明</h4>
          <ul>
            <li>AI将重新安排当前模板下所有未完成记录的会议时间</li>
            <li>优先考虑项目设置的固定时间</li>
            <li>按照优先级和阶段合理分配时间段</li>
            <li>避免时间冲突，确保合理间隔</li>
            <li>所有新安排的时间都将在当前时间之后</li>
          </ul>
        </div>

        <div class="info-section">
          <h4><i class="el-icon-data-line" /> 当前统计</h4>
          <p>模板：<strong>{{ getCurrentTemplateName() }}</strong></p>
          <p>未完成记录：<strong>{{ getUnfinishedRecordsCount() }}</strong> 条</p>
          <p>涉及项目：<strong>{{ getUniqueProjectsCount() }}</strong> 个</p>
        </div>

        <div class="warning-section">
          <el-alert
            title="注意：此操作将修改所有未完成记录的时间安排，请确认后再继续"
            type="warning"
            :closable="false"
            show-icon
          />
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="showAIRescheduleDialog = false">取 消</el-button>
        <el-button type="primary" :loading="aiRescheduleLoading" @click="executeAIReschedule">
          <i class="el-icon-cpu" /> 确认重新规划
        </el-button>
      </span>
    </el-dialog>

    <!-- 项目状态管理对话框 -->
    <el-dialog
      title="项目订单状态管理"
      :visible.sync="showProjectStatusDialog"
      width="800px"
    >
      <div class="project-status-management">
        <el-alert
          title="在此界面可以统一查看和管理所有项目的订单状态"
          type="info"
          show-icon
          :closable="false"
          style="margin-bottom: 20px;"
        />

        <el-table
          v-loading="projectStatusLoading"
          :data="allProjectStatusList"
          style="width: 100%"
        >
          <el-table-column prop="project_name" label="项目名称" width="200" />
          <el-table-column prop="last_update_by" label="最后更新人" width="120" />
          <el-table-column prop="update_at" label="更新时间" width="160" />
        </el-table>

        <div style="margin-top: 20px; text-align: center;">
          <el-button icon="el-icon-refresh" @click="loadAllProjectStatus">刷新</el-button>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="showProjectStatusDialog = false">关 闭</el-button>
      </span>
    </el-dialog>

    <!-- 确认完成对话框 -->
    <el-dialog
      title="确认完成"
      :visible.sync="showCompleteDialog"
      width="500px"
      :before-close="handleCompleteDialogClose"
    >
      <el-form :model="completeForm" label-width="100px">
        <el-form-item label="完成时间">
          <el-date-picker
            v-model="completeForm.doneAt"
            type="datetime"
            format="yyyy-MM-dd HH:mm"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择实际完成时间"
            style="width: 100%;"
            :picker-options="{
              disabledDate(time) {
                // 不能选择未来时间
                return time.getTime() > Date.now()
              }
            }"
          />
          <div style="font-size: 12px; color: #999; margin-top: 5px;">
            默认为当前时间，可修改为实际完成时间
          </div>
        </el-form-item>

        <el-form-item label="自定义阶段">
          <el-input
            v-model="completeForm.stage"
            placeholder="如: s1, s2等"
            clearable
          />
          <div style="font-size: 12px; color: #999; margin-top: 5px;">
            当前阶段：{{ completeForm.currentStage || '无' }}
          </div>
        </el-form-item>

        <el-form-item label="完成备注">
          <el-input
            v-model="completeForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入完成的具体内容描述..."
            clearable
          />
          <div style="font-size: 12px; color: #999; margin-top: 5px;">
            描述本次完成的具体工作内容（可选）
          </div>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="showCompleteDialog = false">取 消</el-button>
        <el-button
          type="primary"
          :loading="completeLoading"
          :disabled="!completeForm.stage.trim()"
          @click="confirmComplete"
        >
          确定完成
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  Get, Post, Put,
  GetTemplate, PostTemplate, PutTemplate, DeleteTemplate, AutoScheduleAllProjects,
  GetRecord, PostRecord, PutRecord, CompleteRecord, NotifyScheduleRecord, DeleteRecord,
  AIRescheduleRecords
} from '@/api/erp/schedule'
import { CRMGetProjectUsers as GetUsers } from '@/api/crm/crmmanage'
import { Get as GetProjects } from '@/api/erp/elicink/project.js'
import { GetProjectOrderState, UpdateProjectOrderState } from '@/api/erp/elicink/project_order_state.js'
import qs from 'qs'

export default {
  name: 'Schedule',
  data() {
    return {
      // 模板相关
      selectedTemplateId: null,
      templateList: [],
      templateLoading: false,

      // 项目订单状态
      projectOrderStates: {}, // {project_id: {current_state_id, available_states}}
      allProjectStatusList: [], // 所有项目状态列表
      projectStatusLoading: false,

      // 记录相关
      recordList: [],
      completedRecordsList: [], // 存储所有已完成的历史日程
      recordLoading: false,
      selectedRecords: [],
      allRecordsForConflict: [], // 所有记录用于冲突检测

      // 分页
      listQuery: {
        page: 1,
        pageSize: 20
      },
      total: 0,

      // 对话框
      showTemplateDialog: false,
      showEditDialog: false,
      showNotifyDialog: false,
      showCreateDialog: false,
      showScheduleDialog: false,
      showAIRescheduleDialog: false,
      showAutoScheduleDialog: false,
      isSavingSchedule: false, // 防止重复提交日程设置
      showProjectStatusDialog: false,
      showCompleteDialog: false,
      aiRescheduleLoading: false,
      completeLoading: false,
      viewMode: 'table', // 'table' 或 'timeline'
      activeTab: 'list',

      // 模板表单
      templateForm: {
        name: '',
        title: '',
        content: '',
        stage: '',
        schedule_type: 'task',
        priority: 'normal',
        is_repeat: false,
        repeat_type: 'weekly',
        repeat_interval: 1,
        default_duration_hours: null,
        is_active: true,
        applicable_project_ids: []
      },
      templateRules: {
        name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
        title: [{ required: true, message: '请输入日程标题', trigger: 'blur' }]
      },
      editingTemplate: null,

      // 编辑记录表单
      editForm: {
        id: null,
        schedule_time: '',
        note: '',
        is_time_fixed: false
      },

      // 钉钉通知表单
      notifyForm: {
        record_id: null,
        record_info: null,
        message: '收到请确认'
      },

      // 创建记录表单
      createForm: {
        project_id: null,
        schedule_template_id: null,
        schedule_title: '',
        schedule_time: '',
        user_id: null,
        note: '',
        schedule_stage: '',
        schedule_priority: 'normal'
      },
      createRules: {
        project_id: [{ required: true, message: '请选择项目', trigger: 'change' }],
        schedule_time: [{ required: true, message: '请选择计划时间', trigger: 'change' }],
        user_id: [{ required: true, message: '请选择负责人', trigger: 'change' }]
      },

      // 项目列表
      projectList: [],

      // 项目成员列表
      projectUserList: [],

      // 设置日程表单
      scheduleForm: {
        id: null,
        project_id: null,
        project_name: '',
        template_id: null,
        template_name: '',
        template_title: '',
        custom_title: '',
        custom_content: '',
        custom_stage: '',
        custom_priority: '',
        use_fixed_time: false,
        fixed_weekday: null,
        fixed_hour: null,
        fixed_minute: null,
        is_active: true
      },
      scheduleRules: {
        // 暂时不需要必填验证，因为大部分字段都是可选的
      },

      // 完成记录表单
      completeForm: {
        recordId: null,
        stage: '',
        content: '',
        currentStage: '',
        doneAt: null // 完成时间
      },

      // 一键分配相关
      autoScheduleStartDate: null,
      lastAutoScheduleDate: null, // 上次自动分配日期
      datePickerOptions: {
        disabledDate(time) {
          // 禁用今天之前的日期
          return time.getTime() < Date.now() - 8.64e7
        }
      },

      // 拖拽相关
      draggedRecord: null,
      isDragging: false
    }
  },

  computed: {
    // 按日期分组的记录
    groupedRecords() {
      if (!this.recordList || this.recordList.length === 0) return []

      const groups = {}

      this.recordList.forEach(record => {
        if (!record.schedule_time) return

        const date = new Date(record.schedule_time).toDateString()
        if (!groups[date]) {
          groups[date] = {
            date: date,
            records: []
          }
        }
        groups[date].records.push(record)
      })

      // 按日期排序分组
      const sortedGroups = Object.values(groups).sort((a, b) => {
        return new Date(a.date) - new Date(b.date)
      })

      // 每个分组内按时间排序
      sortedGroups.forEach(group => {
        group.records.sort((a, b) => {
          return new Date(a.schedule_time) - new Date(b.schedule_time)
        })
      })

      return sortedGroups
    }
  },

  created() {
    this.loadTemplates()
    this.loadProjects()
  },

  watch: {
    recordList: {
      handler(newList) {
        // 当记录列表更新时，加载各项目的订单状态
        if (newList && newList.length > 0) {
          const projectIds = [...new Set(newList.map(r => r.project_id))]
          projectIds.forEach(projectId => {
            if (!this.projectOrderStates[projectId]) {
              this.loadProjectOrderState(projectId)
            }
          })
        }
      },
      immediate: true
    },
    showProjectStatusDialog(val) {
      // 打开对话框时加载所有项目状态
      if (val) {
        this.loadAllProjectStatus()
      }
    }
  },

  methods: {
    // 加载项目订单状态
    async loadProjectOrderState(projectId) {
      try {
        const response = await GetProjectOrderState(projectId)
        if (response.data.success) {
          this.$set(this.projectOrderStates, projectId, {
            current_state_id: response.data.data.state_config.current_state_id,
            available_states: response.data.data.available_states,
            state_config: response.data.data.state_config
          })
        }
      } catch (error) {
        console.error('加载项目订单状态失败:', error)
      }
    },

    // 更新项目订单状态
    async updateProjectOrderState(projectId) {
      const stateData = this.projectOrderStates[projectId]
      if (!stateData) return

      try {
        const response = await UpdateProjectOrderState({
          project_id: projectId,
          state_id: stateData.current_state_id
        })

        if (response.data.success) {
          this.$message.success('状态更新成功')
          // 更新本地数据
          if (stateData.state_config) {
            const selectedState = stateData.available_states.find(s => s.id === stateData.current_state_id)
            if (selectedState) {
              stateData.state_config.current_state_name = selectedState.name
              stateData.state_config.current_state_color = selectedState.color
            }
          }
        } else {
          this.$message.error(response.data.msg || '状态更新失败')
          // 恢复原值
          this.loadProjectOrderState(projectId)
        }
      } catch (error) {
        this.$message.error('状态更新失败')
        console.error('更新项目订单状态失败:', error)
        // 恢复原值
        this.loadProjectOrderState(projectId)
      }
    },

    // 加载所有项目的状态（用于管理对话框）
    async loadAllProjectStatus() {
      this.projectStatusLoading = true
      try {
        // 获取所有项目
        const projectResponse = await GetProjects()
        if (projectResponse.data && projectResponse.data.length > 0) {
          const projects = projectResponse.data

          // 并行加载每个项目的状态信息
          const statusPromises = projects.map(async project => {
            try {
              const response = await GetProjectOrderState(project.id)
              if (response.data.success) {
                return {
                  project_id: project.id,
                  project_name: project.name,
                  current_state_id: response.data.data.state_config.current_state_id,
                  available_states: response.data.data.available_states,
                  last_update_by: response.data.data.state_config.last_update_by,
                  update_at: response.data.data.state_config.update_at
                }
              }
            } catch (error) {
              console.error(`加载项目 ${project.name} 的状态失败:`, error)
              return {
                project_id: project.id,
                project_name: project.name,
                current_state_id: null,
                available_states: [],
                last_update_by: '',
                update_at: ''
              }
            }
          })

          this.allProjectStatusList = await Promise.all(statusPromises)
        }
      } catch (error) {
        this.$message.error('加载项目状态列表失败')
        console.error('加载项目状态列表失败:', error)
      } finally {
        this.projectStatusLoading = false
      }
    },

    // 从管理对话框更新项目状态
    async updateProjectStatusFromDialog(row) {
      try {
        const response = await UpdateProjectOrderState({
          project_id: row.project_id,
          state_id: row.current_state_id
        })

        if (response.data.success) {
          this.$message.success(`${row.project_name} 状态更新成功`)
          // 更新表格中的显示
          row.last_update_by = response.data.data.last_update_by
          row.update_at = response.data.data.update_at

          // 同步更新主表格中的状态（如果存在）
          if (this.projectOrderStates[row.project_id]) {
            this.projectOrderStates[row.project_id].current_state_id = row.current_state_id
          }
        } else {
          this.$message.error(response.data.msg || '状态更新失败')
          // 重新加载获取正确的值
          this.loadAllProjectStatus()
        }
      } catch (error) {
        this.$message.error('状态更新失败')
        console.error('更新项目状态失败:', error)
        // 重新加载获取正确的值
        this.loadAllProjectStatus()
      }
    },

    // 加载模板列表
    async loadTemplates() {
      try {
        this.templateLoading = true
        const response = await GetTemplate()
        if (response.success) {
          this.templateList = response.data.data || []
          // 默认选择第一个模板
          if (this.templateList.length > 0 && !this.selectedTemplateId) {
            this.selectedTemplateId = this.templateList[0].id
            this.loadRecords()
          }
        }
      } catch (error) {
        this.$message.error('加载模板列表失败')
      } finally {
        this.templateLoading = false
      }
    },

    // 加载项目列表
    async loadProjects() {
      try {
        // 参考 projectManage.vue 的获取方式
        const response = await GetProjects(null, qs.stringify({
          pagesize: 1000, // 获取所有项目
          page: 1
        }))
        if (response.success) {
          // 只获取启用的项目
          this.projectList = (response.data.data || []).filter(project => project.isEnable)

          // 如果有项目且创建表单还没有选择项目，自动选择第一个项目
          if (this.projectList.length > 0 && !this.createForm.project_id) {
            this.createForm.project_id = this.projectList[0].id
            // 自动加载第一个项目的成员列表
            this.handleProjectChange(this.createForm.project_id)
          }
        }
      } catch (error) {
        console.error('加载项目列表失败:', error)
      }
    },

    // 模板选择变化
    handleTemplateChange(templateId) {
      this.selectedTemplateId = templateId

      // 如果创建表单已经打开，同时更新表单中的模板信息
      if (this.showCreateDialog) {
        this.createForm.schedule_template_id = templateId
        const selectedTemplate = this.templateList.find(template => template.id === templateId)
        if (selectedTemplate) {
          this.createForm.schedule_title = selectedTemplate.title
        }
      }

      // 获取上次分配日期
      const savedDate = localStorage.getItem(`lastAutoSchedule_${templateId}`)
      this.lastAutoScheduleDate = savedDate || null

      this.loadRecords()
    },

    // 加载日程记录列表
    async loadRecords() {
      if (!this.selectedTemplateId) return

      // 防止重复调用
      if (this.recordLoading) {
        return
      }

      try {
        this.recordLoading = true

        // 先加载所有未完成的记录用于冲突检测和分页显示
        const allParams = new URLSearchParams({
          schedule__template_id: this.selectedTemplateId,
          is_done: 'false',
          page: 1,
          pagesize: 1000 // 获取所有未完成记录
        })

        const allResponse = await GetRecord(null, allParams.toString())
        if (allResponse.success) {
          const allRecords = allResponse.data.data || []
          this.total = allResponse.data.total || 0

          // 设置冲突检测数据
          this.allRecordsForConflict = allRecords

          // 手动分页处理显示数据
          const startIndex = (this.listQuery.page - 1) * this.listQuery.pageSize
          const endIndex = startIndex + this.listQuery.pageSize
          this.recordList = allRecords.slice(startIndex, endIndex)
        }

        // 同时加载所有已完成的记录（历史日程）
        const completedParams = new URLSearchParams({
          schedule__template_id: this.selectedTemplateId,
          is_done: 'true',
          page: 1,
          pagesize: 1000 // 获取所有已完成记录
        })

        const completedResponse = await GetRecord(null, completedParams.toString())
        if (completedResponse.success) {
          this.completedRecordsList = completedResponse.data.data || []
        }
      } catch (error) {
        this.$message.error('加载日程记录失败')
      } finally {
        this.recordLoading = false
      }
    },

    // 刷新记录
    refreshRecords() {
      // 防止重复点击
      if (this.recordLoading) {
        return
      }
      this.loadRecords()
    },

    // 分页处理
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.loadRecords()
    },

    handlePageChange(val) {
      this.listQuery.page = val
      this.loadRecords()
    },

    // 选择变化
    handleSelectionChange(selection) {
      this.selectedRecords = selection
    },

    // 更新记录时间
    async updateRecordTime(record) {
      try {
        // 手动设置时间时，自动将时间设为固定
        const updateData = {
          schedule_time: record.schedule_time,
          is_time_fixed: true
        }

        const response = await PutRecord(record.id, updateData)
        if (response.success) {
          // 更新本地数据
          record.is_time_fixed = true
          this.$message.success('时间已更新并设为固定')
          return response
        } else {
          this.$message.error('时间更新失败')
          return false
        }
      } catch (error) {
        this.$message.error('时间更新失败')
        return false
      }
    },

    // 完成记录
    completeRecord(record) {
      const currentStage = (record.schedule && record.schedule.stage) || record.schedule_stage || ''

      // 重置表单数据
      this.completeForm = {
        recordId: record.id,
        stage: currentStage,
        content: '',
        currentStage: currentStage,
        doneAt: new Date().toISOString().slice(0, 19).replace('T', ' '), // 默认为当前时间
        projectId: record.project_id,
        projectName: record.project_name || record.project?.name || '未知项目',
        scheduleTitle: record.schedule_title || (record.schedule && record.schedule.title) || '未命名日程'
      }

      // 显示对话框
      this.showCompleteDialog = true
    },

    // 确认完成
    async confirmComplete() {
      if (!this.completeForm.stage.trim()) {
        this.$message.warning('请输入阶段信息')
        return
      }

      this.completeLoading = true
      try {
        // 后端会自动处理：1.保存自定义阶段到项目参数 2.发送钉钉群通知
        const response = await CompleteRecord(this.completeForm.recordId, {
          stage: this.completeForm.stage.trim(),
          content: this.completeForm.content.trim() || undefined, // 完成内容
          done_at: this.completeForm.doneAt, // 完成时间
          note: this.completeForm.content.trim() || undefined // 备注
        })

        if (response.success) {
          this.$message.success('标记完成成功')
          this.showCompleteDialog = false
          this.loadRecords() // 刷新列表
        }
      } catch (error) {
        this.$message.error('操作失败: ' + (error.message || '未知错误'))
      } finally {
        this.completeLoading = false
      }
    },

    // 处理完成对话框关闭
    handleCompleteDialogClose() {
      this.showCompleteDialog = false
      // 重置表单
      this.completeForm = {
        recordId: null,
        stage: '',
        content: '',
        currentStage: '',
        doneAt: null,
        projectId: null,
        projectName: '',
        scheduleTitle: ''
      }
    },

    // 编辑记录
    editRecord(record) {
      this.editForm = {
        id: record.id,
        project_id: record.project_id,
        schedule_time: record.schedule_time,
        note: record.note || '',
        is_time_fixed: record.is_time_fixed || false
      }
      // 确保已加载该项目的状态信息
      if (!this.projectOrderStates[record.project_id]) {
        this.loadProjectOrderState(record.project_id)
      }
      this.showEditDialog = true
    },

    // 保存记录编辑
    async saveRecordEdit() {
      try {
        const response = await PutRecord(this.editForm.id, {
          schedule_time: this.editForm.schedule_time,
          note: this.editForm.note,
          is_time_fixed: this.editForm.is_time_fixed
        })
        if (response.success) {
          this.$message.success('更新成功')
          this.showEditDialog = false
          this.loadRecords()
        }
      } catch (error) {
        this.$message.error('更新失败')
      }
    },

    // 一键分配所有项目日程
    async autoScheduleAllProjects() {
      if (!this.selectedTemplateId) {
        this.$message.warning('请先选择模板')
        return
      }

      // 设置默认开始日期为明天
      const tomorrow = new Date()
      tomorrow.setDate(tomorrow.getDate() + 1)
      this.autoScheduleStartDate = tomorrow.toISOString().split('T')[0]

      // 显示日期选择对话框
      this.showAutoScheduleDialog = true
    },

    // 执行自动分配
    async executeAutoSchedule() {
      if (!this.autoScheduleStartDate) {
        this.$message.warning('请选择开始日期')
        return
      }

      // 获取模板关联的项目数量
      const templateProjectsCount = this.getTemplateProjectsCount()
      if (templateProjectsCount === 0) {
        this.$message.warning('当前模板没有关联任何项目')
        return
      }

      try {
        const loading = this.$loading({
          lock: true,
          text: `AI正在为 ${templateProjectsCount} 个项目智能安排日程...`,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        // 调用自动分配API
        // 后端会根据模板的 applicable_projects 字段，只为关联的项目分配日程
        const response = await AutoScheduleAllProjects(this.selectedTemplateId, {
          start_date: this.autoScheduleStartDate
        })
        loading.close()

        if (response.success) {
          // 保存上次分配日期
          this.lastAutoScheduleDate = new Date().toLocaleString('zh-CN')
          localStorage.setItem(`lastAutoSchedule_${this.selectedTemplateId}`, this.lastAutoScheduleDate)

          // 检查分配结果
          const assignedCount = response.data?.assigned_count || 0
          const expectedCount = templateProjectsCount

          if (assignedCount !== expectedCount) {
            this.$alert(
              `<div>
                <p style="color: #E6A23C;">⚠️ 分配数量不匹配！</p>
                <p>预期分配：<strong>${expectedCount}</strong> 个项目</p>
                <p>实际分配：<strong style="color: #F56C6C;">${assignedCount}</strong> 个项目</p>
                <p style="margin-top: 10px;">请检查后端日志以了解详情</p>
              </div>`,
              '分配结果提示',
              {
                dangerouslyUseHTMLString: true,
                confirmButtonText: '确定',
                type: 'warning'
              }
            )
          } else {
            this.$message.success(`成功为 ${assignedCount} 个项目分配日程`)
          }

          this.showAutoScheduleDialog = false
          this.loadRecords() // 刷新记录列表
        } else {
          this.$message.error(response.msg || '自动分配失败')
        }
      } catch (error) {
        this.$message.error('自动分配失败: ' + (error.message || '未知错误'))
      }
    },

    // 显示创建模板
    showCreateTemplate() {
      this.editingTemplate = null
      this.resetTemplateForm()
      this.activeTab = 'edit'
    },

    // 编辑模板
    async editTemplate(template) {
      console.log('编辑模板数据:', template) // 调试信息
      this.editingTemplate = template

      try {
        // 获取模板详情，确保有完整的关联项目信息
        const response = await GetTemplate(template.id)
        const fullTemplateData = response.success ? response.data : template
        console.log('模板详情数据:', fullTemplateData) // 调试信息

        // 处理适用项目ID列表
        let applicable_project_ids = []
        if (fullTemplateData.applicable_project_ids && Array.isArray(fullTemplateData.applicable_project_ids)) {
          applicable_project_ids = fullTemplateData.applicable_project_ids
        } else if (fullTemplateData.applicable_projects && Array.isArray(fullTemplateData.applicable_projects)) {
          // 如果后端返回的是项目对象数组，提取ID
          applicable_project_ids = fullTemplateData.applicable_projects.map(project => project.id || project)
        } else if (template.applicable_projects_names && template.applicable_projects_names.length > 0) {
          // 通过项目名称匹配ID（备用方案）
          applicable_project_ids = this.projectList
            .filter(project => template.applicable_projects_names.includes(project.name))
            .map(project => project.id)
        }

        this.templateForm = {
          ...fullTemplateData,
          applicable_project_ids: applicable_project_ids
        }
        console.log('处理后的表单数据:', this.templateForm) // 调试信息
      } catch (error) {
        console.error('获取模板详情失败:', error)
        // 降级处理
        this.templateForm = {
          ...template,
          applicable_project_ids: []
        }
      }

      this.activeTab = 'edit'
    },

    // 保存模板
    async saveTemplate() {
      this.$refs.templateForm.validate(async(valid) => {
        if (valid) {
          try {
            let response
            if (this.editingTemplate) {
              // 更新模板
              response = await PutTemplate(this.editingTemplate.id, this.templateForm)
            } else {
              // 创建模板
              response = await PostTemplate(this.templateForm)
            }

            if (response.success) {
              this.$message.success(this.editingTemplate ? '更新成功' : '创建成功')
              this.activeTab = 'list'
              this.loadTemplates()
            }
          } catch (error) {
            this.$message.error('保存失败')
          }
        }
      })
    },

    // 删除模板
    deleteTemplate(template) {
      this.$confirm('确定要删除该模板吗？', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          const response = await DeleteTemplate(template.id)
          if (response.success) {
            this.$message.success('删除成功')
            this.loadTemplates()
          }
        } catch (error) {
          this.$message.error('删除失败')
        }
      })
    },

    // 重置模板表单
    resetTemplateForm() {
      this.templateForm = {
        name: '',
        title: '',
        content: '',
        stage: '',
        schedule_type: 'task',
        priority: 'normal',
        is_repeat: false,
        repeat_type: 'weekly',
        repeat_interval: 1,
        default_duration_hours: null,
        is_active: true,
        applicable_project_ids: []
      }
      this.editingTemplate = null
      if (this.$refs.templateForm) {
        this.$refs.templateForm.clearValidate()
      }
    },

    // 获取优先级类型
    getPriorityType(priority) {
      const typeMap = {
        'low': 'info',
        'normal': '',
        'high': 'warning',
        'urgent': 'danger'
      }
      return typeMap[priority] || ''
    },

    // 获取优先级文本
    getPriorityText(priority) {
      const textMap = {
        'low': '低',
        'normal': '普通',
        'high': '高',
        'urgent': '紧急'
      }
      return textMap[priority] || priority
    },

    // 发送钉钉通知
    sendDingTalkNotification(record) {
      // 设置通知表单数据
      this.notifyForm = {
        record_id: record.id,
        record_info: record,
        message: '收到请确认'
      }
      // 显示对话框
      this.showNotifyDialog = true
    },

    // 确认发送通知
    async confirmSendNotification() {
      if (!this.notifyForm.message.trim()) {
        this.$message.warning('请输入自定义消息内容')
        return
      }

      try {
        const loading = this.$loading({
          lock: true,
          text: '正在发送钉钉通知...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        const response = await NotifyScheduleRecord(this.notifyForm.record_id, {
          message: this.notifyForm.message
        })
        loading.close()

        if (response.success) {
          this.$message.success(response.msg || '钉钉通知发送成功')
          this.showNotifyDialog = false

          // 更新本地记录的通知状态
          const record = this.recordList.find(r => r.id === this.notifyForm.record_id)
          if (record) {
            record.send_notice = true
          }

          // 同时更新冲突检测用的记录列表
          const conflictRecord = this.allRecordsForConflict.find(r => r.id === this.notifyForm.record_id)
          if (conflictRecord) {
            conflictRecord.send_notice = true
          }
        } else {
          // 后端返回success: false的情况
          this.$message.error(response.msg || '钉钉通知发送失败')
        }
      } catch (error) {
        console.error('发送钉钉通知异常:', error)
        this.$message.error('钉钉通知发送失败: ' + (error.message || '未知错误'))
      }
    },

    // 批量标记完成
    async batchCompleteRecords() {
      if (this.selectedRecords.length === 0) {
        this.$message.warning('请先选择要操作的记录')
        return
      }

      this.$confirm(`确定要将选中的 ${this.selectedRecords.length} 条记录标记为完成吗？`, '批量标记完成', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const loading = this.$loading({
          lock: true,
          text: `正在批量标记完成... (0/${this.selectedRecords.length})`,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        let successCount = 0
        let failCount = 0
        const total = this.selectedRecords.length

        try {
          for (let i = 0; i < this.selectedRecords.length; i++) {
            const record = this.selectedRecords[i]
            loading.text = `正在批量标记完成... (${i + 1}/${total})`

            try {
              const response = await CompleteRecord(record.id, {})
              if (response.success) {
                successCount++
              } else {
                failCount++
              }
            } catch (error) {
              failCount++
              console.error(`标记完成失败 - 记录ID: ${record.id}`, error)
            }
          }

          loading.close()

          if (failCount === 0) {
            this.$message.success(`批量标记完成成功！共处理 ${successCount} 条记录`)
          } else {
            this.$message.warning(`批量操作完成！成功 ${successCount} 条，失败 ${failCount} 条`)
          }

          this.loadRecords() // 刷新列表
        } catch (error) {
          loading.close()
          this.$message.error('批量操作失败')
        }
      })
    },

    // 批量删除
    async batchDeleteRecords() {
      if (this.selectedRecords.length === 0) {
        this.$message.warning('请先选择要删除的记录')
        return
      }

      this.$confirm(`确定要删除选中的 ${this.selectedRecords.length} 条记录吗？删除后无法恢复！`, '批量删除', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const loading = this.$loading({
          lock: true,
          text: `正在批量删除... (0/${this.selectedRecords.length})`,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        let successCount = 0
        let failCount = 0
        const total = this.selectedRecords.length

        try {
          for (let i = 0; i < this.selectedRecords.length; i++) {
            const record = this.selectedRecords[i]
            loading.text = `正在批量删除... (${i + 1}/${total})`

            try {
              const response = await DeleteRecord(record.id)
              if (response.success) {
                successCount++
              } else {
                failCount++
              }
            } catch (error) {
              failCount++
              console.error(`删除失败 - 记录ID: ${record.id}`, error)
            }
          }

          loading.close()

          if (failCount === 0) {
            this.$message.success(`批量删除成功！共删除 ${successCount} 条记录`)
          } else {
            this.$message.warning(`批量操作完成！成功 ${successCount} 条，失败 ${failCount} 条`)
          }

          this.loadRecords() // 刷新列表
        } catch (error) {
          loading.close()
          this.$message.error('批量删除失败')
        }
      })
    },

    // 显示创建记录对话框
    showCreateRecord() {
      this.resetCreateForm()
      this.createForm.schedule_template_id = this.selectedTemplateId

      // 自动从选择的模板中获取标题
      if (this.selectedTemplateId) {
        const selectedTemplate = this.templateList.find(template => template.id === this.selectedTemplateId)
        if (selectedTemplate) {
          this.createForm.schedule_title = selectedTemplate.title
        }
      }

      // 如果有项目列表且还没有选择项目，自动选择第一个项目
      if (this.projectList.length > 0 && !this.createForm.project_id) {
        this.createForm.project_id = this.projectList[0].id
        // 自动加载项目成员列表
        this.handleProjectChange(this.createForm.project_id)
      }

      this.showCreateDialog = true
    },

    // 重置创建记录表单
    resetCreateForm() {
      this.createForm = {
        project_id: null,
        schedule_template_id: null,
        schedule_title: '',
        schedule_time: '',
        user_id: null,
        note: '',
        schedule_stage: '',
        schedule_priority: 'normal'
      }
      // 清空项目成员列表
      this.projectUserList = []
      if (this.$refs.createForm) {
        this.$refs.createForm.clearValidate()
      }
    },

    // 处理项目选择变化
    async handleProjectChange(projectId) {
      if (projectId) {
        try {
          // 清空之前选择的负责人
          this.createForm.user_id = null
          // 获取项目成员
          const response = await GetUsers(qs.stringify({
            project_id: projectId,
            pagesize: 1000,
            page: 1
          }))
          if (response.success && response.data && response.data.data) {
            this.projectUserList = response.data.data
            console.log(this.projectUserList)
          } else {
            this.projectUserList = []
            this.$message.warning('该项目暂无成员')
          }
        } catch (error) {
          console.error('获取项目成员失败:', error)
          this.projectUserList = []
          this.$message.error('获取项目成员失败')
        }
      } else {
        this.projectUserList = []
        this.createForm.user_id = null
      }
    },

    // 保存创建记录
    async saveCreateRecord() {
      this.$refs.createForm.validate(async(valid) => {
        if (valid) {
          try {
            const loading = this.$loading({
              lock: true,
              text: '正在创建日程记录...',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })

            const response = await PostRecord(this.createForm)
            loading.close()

            if (response.success) {
              this.$message.success('创建成功')
              this.showCreateDialog = false
              this.loadRecords() // 刷新列表
            }
          } catch (error) {
            this.$message.error('创建失败: ' + (error.message || '未知错误'))
          }
        }
      })
    },

    // 设置明天9点的时间
    setTomorrowTime() {
      const tomorrow = new Date()
      tomorrow.setDate(tomorrow.getDate() + 1)
      tomorrow.setHours(9, 0, 0, 0)
      this.createForm.schedule_time = this.formatDateTime(tomorrow)
    },

    // 设置后天9点的时间
    setDayAfterTomorrowTime() {
      const dayAfterTomorrow = new Date()
      dayAfterTomorrow.setDate(dayAfterTomorrow.getDate() + 2)
      dayAfterTomorrow.setHours(9, 0, 0, 0)
      this.createForm.schedule_time = this.formatDateTime(dayAfterTomorrow)
    },

    // 格式化日期时间为指定格式
    formatDateTime(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },

    // 检测时间冲突
    checkTimeConflict(record) {
      if (!record.schedule_time) {
        return false
      }

      // 检测未完成的记录冲突（allRecordsForConflict已经只包含未完成的记录）
      const conflictRecord = this.allRecordsForConflict.find(otherRecord => {
        if (otherRecord.id === record.id) return false // 排除自己
        if (!otherRecord.schedule_time) return false

        // 直接比较时间字符串
        return otherRecord.schedule_time === record.schedule_time
      })

      return !!conflictRecord
    },

    // 获取建议时间
    getSuggestedTime(record) {
      if (!record.schedule_time) return []

      const recordTime = new Date(record.schedule_time)
      const recordDate = recordTime.toDateString()

      // 定义标准时间段
      const timeSlots = [
        '09:30', '10:30', '11:30',
        '14:30', '15:30', '16:30', '17:30'
      ]

      // 获取同一天的已占用时间段（allRecordsForConflict已经只包含未完成的记录）
      const occupiedTimes = this.allRecordsForConflict
        .filter(otherRecord => {
          if (otherRecord.id === record.id) return false
          if (!otherRecord.schedule_time) return false

          const otherTime = new Date(otherRecord.schedule_time)
          const otherDate = otherTime.toDateString()
          return recordDate === otherDate
        })
        .map(otherRecord => otherRecord.schedule_time)

      // 返回前3个建议时间
      return timeSlots.slice(0, 3).map(slot => {
        const [hour, minute] = slot.split(':')
        const suggestedDate = new Date(recordTime)
        suggestedDate.setHours(parseInt(hour), parseInt(minute), 0, 0)
        const suggestedDateTime = this.formatDateTime(suggestedDate)

        return {
          time: slot,
          datetime: suggestedDateTime
        }
      }).filter(suggestion => {
        // 过滤掉已经被占用的时间
        return !occupiedTimes.includes(suggestion.datetime)
      })
    },

    // 应用建议时间
    async applySuggestedTime(record, suggestedDateTime) {
      try {
        record.schedule_time = suggestedDateTime
        const response = await this.updateRecordTime(record)
        if (response !== false) { // updateRecordTime 成功
          this.$message.success('时间已更新为建议时间')
          // 强制刷新视图以更新冲突检测
          this.$forceUpdate()
        }
      } catch (error) {
        this.$message.error('应用建议时间失败')
      }
    },

    // 切换时间固定状态
    async toggleTimeFixed(record) {
      try {
        const response = await PutRecord(record.id, {
          is_time_fixed: record.is_time_fixed
        })
        if (response.success) {
          this.$message.success(`时间已设为${record.is_time_fixed ? '固定' : '灵活'}`)
        } else {
          // 如果更新失败，恢复原状态
          record.is_time_fixed = !record.is_time_fixed
          this.$message.error('设置失败')
        }
      } catch (error) {
        // 如果更新失败，恢复原状态
        record.is_time_fixed = !record.is_time_fixed
        this.$message.error('设置失败')
      }
    },

    // 编辑日程设置
    async editSchedule(record) {
      try {
        // 首先获取或创建项目日程实例
        const scheduleResponse = await this.getOrCreateProjectSchedule(record.project_id, this.selectedTemplateId)

        if (scheduleResponse.success) {
          const scheduleData = scheduleResponse.data
          const selectedTemplate = this.templateList.find(t => t.id === this.selectedTemplateId)

          this.scheduleForm = {
            id: scheduleData.id,
            project_id: record.project_id,
            project_name: record.project_name,
            template_id: this.selectedTemplateId,
            template_name: selectedTemplate ? selectedTemplate.name : '',
            template_title: selectedTemplate ? selectedTemplate.title : '',
            custom_title: scheduleData.custom_title || '',
            custom_content: scheduleData.custom_content || '',
            custom_stage: scheduleData.custom_stage || '',
            custom_priority: scheduleData.custom_priority || '',
            use_fixed_time: scheduleData.use_fixed_time || false,
            fixed_weekday: scheduleData.fixed_weekday,
            fixed_hour: scheduleData.fixed_hour,
            fixed_minute: scheduleData.fixed_minute,
            is_active: scheduleData.is_active !== undefined ? scheduleData.is_active : true
          }

          this.showScheduleDialog = true
        }
      } catch (error) {
        this.$message.error('获取日程设置失败')
        console.error('获取日程设置失败:', error)
      }
    },

    // 获取或创建项目日程实例
    async getOrCreateProjectSchedule(projectId, templateId) {
      try {
        // 首先尝试获取现有的项目日程
        const params = new URLSearchParams({
          project_id: projectId,
          template_id: templateId
        })

        const getResponse = await Get(null, params.toString())

        if (getResponse.success && getResponse.data.data && getResponse.data.data.length > 0) {
          // 找到现有的日程实例
          return {
            success: true,
            data: getResponse.data.data[0]
          }
        } else {
          // 创建新的日程实例
          const createData = {
            project: projectId,
            template: templateId,
            is_active: true
          }

          const createResponse = await Post(createData)
          return createResponse
        }
      } catch (error) {
        console.error('获取或创建项目日程失败:', error)
        throw error
      }
    },

    // 保存日程设置
    async saveScheduleSettings() {
      // 防止重复提交
      if (this.isSavingSchedule) {
        return
      }

      this.isSavingSchedule = true
      let loading = null

      try {
        loading = this.$loading({
          lock: true,
          text: '正在保存日程设置...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        const updateData = {
          custom_title: this.scheduleForm.custom_title || null,
          custom_content: this.scheduleForm.custom_content || null,
          custom_stage: this.scheduleForm.custom_stage || null,
          custom_priority: this.scheduleForm.custom_priority || null,
          use_fixed_time: this.scheduleForm.use_fixed_time,
          fixed_weekday: this.scheduleForm.use_fixed_time ? this.scheduleForm.fixed_weekday : null,
          fixed_hour: this.scheduleForm.use_fixed_time ? this.scheduleForm.fixed_hour : null,
          fixed_minute: this.scheduleForm.use_fixed_time ? this.scheduleForm.fixed_minute : null,
          is_active: this.scheduleForm.is_active
        }

        const response = await Put(this.scheduleForm.id, updateData)

        if (response.success) {
          this.$message.success('日程设置保存成功')
          this.showScheduleDialog = false

          // 刷新列表以显示更新后的数据
          await this.loadRecords()

          // 如果有项目订单状态，也刷新状态
          if (this.scheduleForm.project_id) {
            await this.loadProjectOrderState(this.scheduleForm.project_id)
          }
        } else {
          throw new Error(response.msg || '保存失败')
        }
      } catch (error) {
        this.$message.error('保存日程设置失败: ' + (error.message || '未知错误'))
        console.error('保存日程设置失败:', error)
      } finally {
        this.isSavingSchedule = false
        if (loading) {
          loading.close()
        }
      }
    },

    // 重置日程设置表单
    resetScheduleForm() {
      this.scheduleForm = {
        id: null,
        project_id: null,
        project_name: '',
        template_id: null,
        template_name: '',
        template_title: '',
        custom_title: '',
        custom_content: '',
        custom_stage: '',
        custom_priority: '',
        use_fixed_time: false,
        fixed_weekday: null,
        fixed_hour: null,
        fixed_minute: null,
        is_active: true
      }
      if (this.$refs.scheduleForm) {
        this.$refs.scheduleForm.clearValidate()
      }
    },

    // 显示AI重新规划对话框
    showAIRescheduleConfirm() {
      if (!this.selectedTemplateId) {
        this.$message.warning('请先选择模板')
        return
      }
      this.showAIRescheduleDialog = true
    },

    // 获取当前模板名称
    getCurrentTemplateName() {
      const template = this.templateList.find(t => t.id === this.selectedTemplateId)
      return template ? template.name : '未知模板'
    },

    // 获取未完成记录数量
    getUnfinishedRecordsCount() {
      return this.total || 0
    },

    // 获取涉及的项目数量
    getUniqueProjectsCount() {
      const uniqueProjects = new Set(this.recordList.map(record => record.project_id))
      return uniqueProjects.size
    },

    // 获取记录中的项目数量
    getUniqueProjectsInRecords() {
      const uniqueProjects = new Set(this.recordList.map(record => record.project_id))
      return uniqueProjects.size
    },

    // 获取模板关联的项目数量
    getTemplateProjectsCount() {
      const template = this.templateList.find(t => t.id === this.selectedTemplateId)
      if (template && template.applicable_project_ids) {
        return template.applicable_project_ids.length
      }
      return 0
    },

    // 格式化上次分配日期
    formatLastScheduleDate(date) {
      if (!date) return '未知'
      // 如果是字符串，直接返回
      if (typeof date === 'string') {
        return date
      }
      // 如果是日期对象，格式化
      if (date instanceof Date) {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        return `${year}-${month}-${day} ${hours}:${minutes}`
      }
      return date
    },

    // 获取距离上次完成的时间间隔
    getTimeIntervalFromLastCompleted(projectId) {
      // 获取该项目已完成的记录
      const completedRecords = this.getProjectCompletedRecords(projectId)

      if (!completedRecords || completedRecords.length === 0) {
        return null
      }

      // 获取最近完成的记录（已经按时间降序排列，第一个就是最近的）
      const lastCompleted = completedRecords[0]
      // 优先使用实际完成时间，如果没有则使用计划时间（兼容旧数据）
      const lastCompletedTime = new Date(lastCompleted.complete_time || lastCompleted.done_at || lastCompleted.schedule_time)
      const now = new Date()

      if (isNaN(lastCompletedTime.getTime())) {
        return null
      }

      // 计算时间差（毫秒）
      const diffMs = now - lastCompletedTime
      const diffMinutes = Math.floor(diffMs / (1000 * 60))
      const diffHours = Math.floor(diffMinutes / 60)
      const diffDays = Math.floor(diffHours / 24)

      // 格式化输出
      if (diffDays > 30) {
        const months = Math.floor(diffDays / 30)
        return `距上次 ${months}个月前`
      } else if (diffDays > 0) {
        const remainingHours = diffHours % 24
        if (remainingHours > 0 && diffDays < 3) {
          return `距上次 ${diffDays}天${remainingHours}小时`
        }
        return `距上次 ${diffDays}天前`
      } else if (diffHours > 0) {
        const remainingMinutes = diffMinutes % 60
        if (remainingMinutes > 0 && diffHours < 6) {
          return `距上次 ${diffHours}小时${remainingMinutes}分钟`
        }
        return `距上次 ${diffHours}小时前`
      } else if (diffMinutes > 0) {
        return `距上次 ${diffMinutes}分钟前`
      } else {
        return '刚刚完成'
      }
    },

    // 获取最近完成的日程详情
    getLastCompletedInfo(projectId) {
      const completedRecords = this.getProjectCompletedRecords(projectId)

      if (!completedRecords || completedRecords.length === 0) {
        return null
      }

      const lastCompleted = completedRecords[0]
      // 优先使用实际完成时间，如果没有则使用计划时间（兼容旧数据）
      const lastCompletedTime = new Date(lastCompleted.complete_time || lastCompleted.done_at || lastCompleted.schedule_time)
      const title = lastCompleted.schedule_title || (lastCompleted.schedule && lastCompleted.schedule.title) || '未命名日程'

      // 格式化日期
      const date = lastCompletedTime.toLocaleDateString('zh-CN', {
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })

      return {
        title: title.length > 15 ? title.substring(0, 15) + '...' : title,
        date: date,
        fullTitle: title
      }
    },

    // 获取距离当前时间的时间差描述
    getTimeFromNow(scheduleTime) {
      if (!scheduleTime) return ''

      const targetTime = new Date(scheduleTime)
      const now = new Date()

      if (isNaN(targetTime.getTime())) {
        return ''
      }

      // 计算时间差（毫秒）
      const diffMs = targetTime - now
      const absDiffMs = Math.abs(diffMs)
      const diffMinutes = Math.floor(absDiffMs / (1000 * 60))
      const diffHours = Math.floor(diffMinutes / 60)
      const diffDays = Math.floor(diffHours / 24)

      let timeStr = ''
      if (diffDays > 0) {
        const remainingHours = diffHours % 24
        if (remainingHours > 0) {
          timeStr = `${diffDays}天${remainingHours}小时`
        } else {
          timeStr = `${diffDays}天`
        }
      } else if (diffHours > 0) {
        const remainingMinutes = diffMinutes % 60
        if (remainingMinutes > 0) {
          timeStr = `${diffHours}小时${remainingMinutes}分钟`
        } else {
          timeStr = `${diffHours}小时`
        }
      } else if (diffMinutes > 0) {
        timeStr = `${diffMinutes}分钟`
      } else {
        timeStr = '现在'
      }

      // 判断是未来还是过去
      if (diffMs > 0) {
        return `${timeStr}后`
      } else if (diffMs < 0) {
        return `${timeStr}前`
      } else {
        return '现在'
      }
    },

    // 执行AI重新规划
    async executeAIReschedule() {
      if (!this.selectedTemplateId) {
        this.$message.warning('请先选择模板')
        return
      }

      try {
        this.aiRescheduleLoading = true

        // 需要获取所有相关的schedule IDs
        const scheduleIds = await this.getAllScheduleIds()

        if (scheduleIds.length === 0) {
          this.$message.warning('没有找到需要重新规划的记录')
          return
        }

        const response = await AIRescheduleRecords({
          schedule_ids: scheduleIds
        })

        if (response.success) {
          const data = response.data
          this.$message.success(response.msg || `成功重新规划了${data.total_updated}条记录`)

          // 显示详细结果
          this.showRescheduleResult(data)

          // 刷新记录列表
          this.loadRecords()

          // 关闭对话框
          this.showAIRescheduleDialog = false
        }
      } catch (error) {
        this.$message.error('AI重新规划失败: ' + (error.message || '未知错误'))
      } finally {
        this.aiRescheduleLoading = false
      }
    },

    // 获取所有相关的schedule IDs
    async getAllScheduleIds() {
      try {
        // 获取当前模板下的所有项目schedule实例
        const params = new URLSearchParams({
          template_id: this.selectedTemplateId,
          page: 1,
          pagesize: 1000
        })

        const response = await Get(null, params.toString())
        if (response.success && response.data.data) {
          return response.data.data.map(schedule => schedule.id)
        }
        return []
      } catch (error) {
        console.error('获取schedule IDs失败:', error)
        return []
      }
    },

    // 显示重新规划结果
    showRescheduleResult(data) {
      const { updated_records, total_updated, original_records_count } = data

      let message = `AI重新规划完成！\n\n`
      message += `原始记录数：${original_records_count}\n`
      message += `成功更新：${total_updated} 条\n\n`

      if (updated_records && updated_records.length > 0) {
        message += `更新详情：\n`
        updated_records.slice(0, 5).forEach((record, index) => {
          message += `${index + 1}. ${record.project_name} - ${record.user_name}\n`
          message += `   ${record.schedule_title}\n`
          message += `   时间: ${new Date(record.new_time).toLocaleString()}\n`
          if (record.reason) {
            message += `   原因: ${record.reason}\n`
          }
          message += `\n`
        })

        if (updated_records.length > 5) {
          message += `... 还有 ${updated_records.length - 5} 条记录被更新\n`
        }
      }

      this.$alert(message, 'AI重新规划结果', {
        confirmButtonText: '确定',
        type: 'success'
      })
    },

    // 视图模式切换
    handleViewModeChange(mode) {
      this.viewMode = mode
    },

    // 格式化日期标题
    formatDateHeader(dateString) {
      const date = new Date(dateString)
      const today = new Date()
      const tomorrow = new Date(today)
      tomorrow.setDate(tomorrow.getDate() + 1)
      const yesterday = new Date(today)
      yesterday.setDate(yesterday.getDate() - 1)

      // 检查是否是今天、明天或昨天
      if (date.toDateString() === today.toDateString()) {
        return `今天 ${date.getMonth() + 1}月${date.getDate()}日`
      } else if (date.toDateString() === tomorrow.toDateString()) {
        return `明天 ${date.getMonth() + 1}月${date.getDate()}日`
      } else if (date.toDateString() === yesterday.toDateString()) {
        return `昨天 ${date.getMonth() + 1}月${date.getDate()}日`
      } else {
        const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
        return `${date.getMonth() + 1}月${date.getDate()}日 ${weekdays[date.getDay()]}`
      }
    },

    // 格式化时间（仅显示时间部分）
    formatTimeOnly(timeString) {
      if (!timeString) return ''
      const date = new Date(timeString)
      return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    },

    // 获取时间线项目类型
    getTimelineItemType(record) {
      if (record.is_done) return 'success'
      if (this.checkTimeConflict(record)) return 'danger'
      return 'primary'
    },

    // 获取时间线项目颜色
    getTimelineItemColor(record) {
      const priority = (record.schedule && record.schedule.priority) || record.schedule_priority
      switch (priority) {
        case 'urgent': return '#f56c6c'
        case 'high': return '#e6a23c'
        case 'normal': return '#409eff'
        case 'low': return '#909399'
        default: return '#409eff'
      }
    },

    // 获取时间线项目大小
    getTimelineItemSize(record) {
      const priority = (record.schedule && record.schedule.priority) || record.schedule_priority
      return priority === 'urgent' ? 'large' : 'normal'
    },

    // 获取卡片样式类
    getCardClass(record) {
      const classes = []
      if (record.is_done) classes.push('completed')
      if (this.checkTimeConflict(record)) classes.push('conflict')

      const priority = (record.schedule && record.schedule.priority) || record.schedule_priority
      if (priority) classes.push(`priority-${priority}`)

      return classes.join(' ')
    },

    // 获取日程图标
    getScheduleIcon(record) {
      const type = (record.schedule && record.schedule.schedule_type) || 'task'
      const iconMap = {
        'meeting': 'el-icon-user-solid',
        'task': 'el-icon-s-order',
        'milestone': 'el-icon-trophy',
        'review': 'el-icon-view',
        'other': 'el-icon-document'
      }
      return iconMap[type] || 'el-icon-s-order'
    },

    // 添加到系统提醒事项
    addToSystemReminder(record) {
      try {
        // 检测是否为苹果系统
        const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0
        const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent)
        const isApple = isMac || isIOS

        if (!isApple) {
          // 非苹果系统，尝试创建ICS文件供下载
          this.downloadICSFile(record)
          return
        }

        // 准备提醒事项数据
        const title = `${record.project_name} - ${(record.schedule && record.schedule.title) || record.schedule_title || '未设置'}`
        const notes = this.buildReminderNotes(record)
        const dueDate = record.schedule_time ? new Date(record.schedule_time) : new Date()

        // 尝试使用多种方式添加到系统
        this.tryAddToAppleReminders(title, notes, dueDate, record)
      } catch (error) {
        console.error('添加系统提醒失败:', error)
        this.$message.error('添加系统提醒失败，请手动添加')
      }
    },

    // 尝试添加到苹果提醒事项
    tryAddToAppleReminders(title, notes, dueDate, record) {
      // 显示选择对话框
      this.$confirm('选择添加方式:', '添加到系统提醒', {
        distinguishCancelAndClose: true,
        confirmButtonText: '日历事件',
        cancelButtonText: '提醒事项',
        customClass: 'system-reminder-dialog'
      }).then(() => {
        // 添加到日历
        this.addViaCalendarURL(title, notes, dueDate)
      }).catch(action => {
        if (action === 'cancel') {
          // 添加到提醒事项
          this.addViaRemindersURL(title, notes, dueDate)
        } else {
          // 用户取消，尝试下载ICS文件
          this.downloadICSFile(record)
        }
      })
    },

    // 通过日历URL添加事件
    addViaCalendarURL(title, notes, dueDate) {
      try {
        // 创建ICS格式的日历事件
        const startDate = new Date(dueDate.getTime() - 15 * 60000) // 提前15分钟开始
        const endDate = dueDate

        const icsContent = this.generateICSContent(title, notes, startDate, endDate)
        const dataURL = `data:text/calendar;charset=utf-8,${encodeURIComponent(icsContent)}`

        // 创建下载链接
        const link = document.createElement('a')
        link.href = dataURL
        link.download = `${title.replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '_')}.ics`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)

        this.$message.success('已生成日历文件，请用系统日历应用打开')
      } catch (error) {
        console.error('创建日历事件失败:', error)
        this.$message.error('创建日历事件失败')
      }
    },

    // 通过提醒事项URL添加
    addViaRemindersURL(title, notes, dueDate) {
      try {
        // 尝试使用提醒事项URL scheme（仅在支持的系统上有效）
        const reminderURL = `x-apple-reminderkit://REMCDReminder?title=${encodeURIComponent(title)}&notes=${encodeURIComponent(notes)}&dueDate=${dueDate.toISOString()}`

        // 创建隐藏的链接尝试打开
        const link = document.createElement('a')
        link.href = reminderURL
        link.style.display = 'none'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)

        // 延迟显示消息，给系统时间处理
        setTimeout(() => {
          this.$message.success('已尝试添加到系统提醒事项')
        }, 500)

        // 备用方案：复制到剪贴板
        setTimeout(() => {
          this.copyToClipboard(title, notes, dueDate)
        }, 2000)
      } catch (error) {
        console.error('添加提醒事项失败:', error)
        this.copyToClipboard(title, notes, dueDate)
      }
    },

    // 下载ICS文件
    downloadICSFile(record) {
      try {
        const title = `${record.project_name} - ${(record.schedule && record.schedule.title) || record.schedule_title || '未设置'}`
        const notes = this.buildReminderNotes(record)
        const dueDate = record.schedule_time ? new Date(record.schedule_time) : new Date()
        const startDate = new Date(dueDate.getTime() - 15 * 60000)

        const icsContent = this.generateICSContent(title, notes, startDate, dueDate)

        const blob = new Blob([icsContent], { type: 'text/calendar;charset=utf-8' })
        const url = window.URL.createObjectURL(blob)

        const link = document.createElement('a')
        link.href = url
        link.download = `${title.replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '_')}.ics`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)

        window.URL.revokeObjectURL(url)

        this.$message.success('已下载日历文件，请用系统日历或提醒应用打开')
      } catch (error) {
        console.error('下载ICS文件失败:', error)
        this.$message.error('下载失败')
      }
    },

    // 复制到剪贴板
    copyToClipboard(title, notes, dueDate) {
      try {
        const text = `提醒事项：\n标题：${title}\n时间：${dueDate.toLocaleString()}\n详情：${notes}`

        // 使用现代浏览器的Clipboard API
        if (navigator.clipboard && window.isSecureContext) {
          navigator.clipboard.writeText(text).then(() => {
            this.$message.success('提醒信息已复制到剪贴板，请手动添加到系统提醒事项')
          })
        } else {
          // 降级方案
          const textArea = document.createElement('textarea')
          textArea.value = text
          textArea.style.position = 'fixed'
          textArea.style.left = '-999999px'
          textArea.style.top = '-999999px'
          document.body.appendChild(textArea)
          textArea.focus()
          textArea.select()

          try {
            document.execCommand('copy')
            this.$message.success('提醒信息已复制到剪贴板，请手动添加到系统提醒事项')
          } catch (error) {
            this.$message.error('复制失败，请手动记录提醒信息')
          }

          document.body.removeChild(textArea)
        }
      } catch (error) {
        console.error('复制到剪贴板失败:', error)
        this.$message.error('复制失败')
      }
    },

    // 构建提醒事项备注
    buildReminderNotes(record) {
      const notes = []
      notes.push(`项目：${record.project_name}`)
      notes.push(`负责人：${record.user_name}`)

      const stage = (record.schedule && record.schedule.stage) || record.schedule_stage
      if (stage) {
        notes.push(`阶段：${stage}`)
      }

      const priority = (record.schedule && record.schedule.priority) || record.schedule_priority
      if (priority) {
        notes.push(`优先级：${this.getPriorityText(priority)}`)
      }

      if (record.note) {
        notes.push(`备注：${record.note}`)
      }

      notes.push(`状态：${record.is_done ? '已完成' : '进行中'}`)
      notes.push(`来源：ERP日程管理系统`)

      return notes.join('\n')
    },

    // 生成ICS文件内容
    generateICSContent(title, notes, startDate, endDate) {
      const formatDate = (date) => {
        return date.toISOString().replace(/[-:]/g, '').split('.')[0] + 'Z'
      }

      const now = new Date()
      const uid = `${now.getTime()}@erp-schedule`

      const icsLines = [
        'BEGIN:VCALENDAR',
        'VERSION:2.0',
        'PRODID:-//ERP Schedule//Schedule Management//CN',
        'CALSCALE:GREGORIAN',
        'METHOD:PUBLISH',
        'BEGIN:VEVENT',
        `UID:${uid}`,
        `DTSTAMP:${formatDate(now)}`,
        `DTSTART:${formatDate(startDate)}`,
        `DTEND:${formatDate(endDate)}`,
        `SUMMARY:${title}`,
        `DESCRIPTION:${notes.replace(/\n/g, '\\n')}`,
        'STATUS:CONFIRMED',
        'TRANSP:OPAQUE',
        'BEGIN:VALARM',
        'TRIGGER:-PT15M',
        'ACTION:DISPLAY',
        `DESCRIPTION:${title}`,
        'END:VALARM',
        'END:VEVENT',
        'END:VCALENDAR'
      ]

      return icsLines.join('\r\n')
    },

    // =================== 拖拽相关方法 ===================

    // 获取行样式
    getRowStyle() {
      return {
        cursor: 'grab'
      }
    },

    // 获取行类名
    getRowClassName({ row, rowIndex }) {
      let className = 'draggable-row'
      if (this.isDragging) {
        if (this.draggedRecord && this.draggedRecord.id === row.id) {
          className += ' dragging'
        } else {
          className += ' drop-target'
        }
      }
      return className
    },

    // 拖拽开始
    handleDragStart(record, event) {
      this.draggedRecord = record
      this.isDragging = true
      event.dataTransfer.effectAllowed = 'move'
      event.dataTransfer.setData('text/html', event.target.outerHTML)

      // 设置拖拽样式
      event.target.style.cursor = 'grabbing'
      event.target.style.opacity = '0.5'

      this.$message.info(`开始拖拽：${record.project_name}`)
    },

    // 拖拽经过
    handleDragOver(event) {
      event.preventDefault()
      event.dataTransfer.dropEffect = 'move'
    },

    // 拖拽进入
    handleDragEnter(event) {
      event.preventDefault()
    },

    // 拖拽结束
    handleDragEnd(event) {
      event.target.style.cursor = 'grab'
      event.target.style.opacity = '1'
      this.isDragging = false
    },

    // 放置
    async handleDrop(targetRecord, event) {
      event.preventDefault()

      if (!this.draggedRecord || this.draggedRecord.id === targetRecord.id) {
        this.draggedRecord = null
        return
      }

      try {
        // 显示确认对话框
        await this.$confirm(
          `确定要交换时间吗？\n\n` +
          `${this.draggedRecord.project_name} (${this.draggedRecord.schedule_time})\n` +
          `↕️\n` +
          `${targetRecord.project_name} (${targetRecord.schedule_time})`,
          '交换时间确认',
          {
            confirmButtonText: '确定交换',
            cancelButtonText: '取消',
            type: 'question'
          }
        )

        await this.swapRecordTimes(this.draggedRecord, targetRecord)
      } catch (error) {
        if (error !== 'cancel') {
          console.error('交换时间失败:', error)
        }
      }

      this.draggedRecord = null
      this.isDragging = false
    },

    // 交换两个记录的时间
    async swapRecordTimes(record1, record2) {
      const loading = this.$loading({
        lock: true,
        text: '正在交换时间...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      try {
        // 临时保存时间
        const tempTime = record1.schedule_time
        const record1Time = record2.schedule_time
        const record2Time = tempTime

        // 同时更新两个记录
        const [response1, response2] = await Promise.all([
          PutRecord(record1.id, {
            schedule_time: record1Time,
            is_time_fixed: record1.is_time_fixed
          }),
          PutRecord(record2.id, {
            schedule_time: record2Time,
            is_time_fixed: record2.is_time_fixed
          })
        ])

        if (response1.success && response2.success) {
          // 更新本地数据
          record1.schedule_time = record1Time
          record2.schedule_time = record2Time

          // 同时更新冲突检测用的记录列表
          const conflictRecord1 = this.allRecordsForConflict.find(r => r.id === record1.id)
          const conflictRecord2 = this.allRecordsForConflict.find(r => r.id === record2.id)
          if (conflictRecord1) conflictRecord1.schedule_time = record1Time
          if (conflictRecord2) conflictRecord2.schedule_time = record2Time

          this.$message.success('时间交换成功！')

          // 强制更新视图以刷新冲突检测
          this.$forceUpdate()
        } else {
          throw new Error('更新失败')
        }
      } catch (error) {
        this.$message.error('时间交换失败: ' + (error.message || '未知错误'))
        console.error('交换时间失败:', error)
      } finally {
        loading.close()
      }
    },

    // 获取项目的已完成记录
    getProjectCompletedRecords(projectId) {
      return this.completedRecordsList
        .filter(record => record.project_id === projectId)
        .sort((a, b) => {
          // 按实际完成时间降序排列，最近的时间排在最前面
          // 优先使用complete_time（done_at转换的），然后是schedule_time（兼容旧数据）
          const timeA = new Date(a.complete_time || a.done_at || a.schedule_time || 0)
          const timeB = new Date(b.complete_time || b.done_at || b.schedule_time || 0)
          return timeB.getTime() - timeA.getTime()
        })
    },

    // 删除已完成的记录
    async deleteCompletedRecord(record) {
      this.$confirm('确定要删除这条历史日程吗？删除后无法恢复！', '确认删除', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          const response = await DeleteRecord(record.id)
          if (response.success) {
            this.$message.success('删除成功')
            // 从本地已完成记录列表中移除
            const index = this.completedRecordsList.findIndex(r => r.id === record.id)
            if (index !== -1) {
              this.completedRecordsList.splice(index, 1)
            }
          } else {
            this.$message.error('删除失败')
          }
        } catch (error) {
          this.$message.error('删除失败: ' + (error.message || '未知错误'))
        }
      })
    },

    // 格式化日期显示
    formatDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      return `${month}-${day} ${hours}:${minutes}`
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.header-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.header-actions {
  text-align: right;
}

.header-actions .el-button {
  margin-left: 10px;
}

.records-section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.template-tabs .el-tabs__content {
  padding: 20px 0;
}

.template-actions {
  text-align: right;
}

.form-actions {
  text-align: center;
  margin-top: 30px;
}

.form-actions .el-button {
  margin: 0 10px;
}

.el-pagination {
  text-align: center;
  margin-top: 20px;
}

.batch-actions {
  background: #f0f9ff;
  border: 1px solid #bae6fd;
  border-radius: 6px;
  padding: 12px 16px;
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.batch-info {
  color: #0369a1;
  font-weight: 500;
}

.batch-buttons .el-button {
  margin-left: 8px;
}

.time-shortcuts {
  text-align: left;
}

.time-shortcuts .el-button {
  font-size: 12px;
}

.time-suggestions {
  padding: 8px;
  background-color: #fff7e6;
  border-radius: 4px;
  border: 1px solid #ffe7ba;
}

.suggestion-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.suggestion-buttons .el-button {
  font-size: 11px;
  padding: 2px 6px;
}

.schedule-info {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.schedule-info div {
  margin-bottom: 8px;
  color: #606266;
}

.schedule-info div:last-child {
  margin-bottom: 0;
}

/* 设置日程对话框样式优化 */
.schedule-form .el-form-item {
  margin-bottom: 20px;
}

.schedule-form .el-select {
  min-width: 120px;
}

.schedule-form .el-input {
  min-width: 200px;
}

/* AI重新规划相关样式 */
.ai-reschedule-section {
  text-align: center;
  padding: 20px;
  margin: 20px 0;
  background: linear-gradient(135deg, #f5f7ff 0%, #e8f4ff 100%);
  border-radius: 8px;
  border: 1px solid #d9ecff;
}

.ai-reschedule-info .info-section {
  margin-bottom: 20px;
}

.ai-reschedule-info h4 {
  color: #409eff;
  margin-bottom: 10px;
  font-size: 14px;
}

.ai-reschedule-info ul {
  text-align: left;
  margin: 0;
  padding-left: 20px;
}

.ai-reschedule-info li {
  margin-bottom: 5px;
  color: #606266;
}

.ai-reschedule-info p {
  margin: 5px 0;
  color: #606266;
}

.warning-section {
  margin-top: 20px;
}

/* 视图切换样式 */
.view-switcher {
  text-align: right;
  margin-bottom: 20px;
  padding: 10px 0;
  border-bottom: 1px solid #ebeef5;
}

/* 时间线视图样式 */
.timeline-view {
  padding: 20px 0;
  max-width: 900px;
  margin: 0 auto;
}

.date-group {
  margin-bottom: 40px;
}

.date-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.date-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.record-count {
  font-size: 14px;
  opacity: 0.9;
}

/* 时间线卡片样式 */
.timeline-card {
  margin-bottom: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  transition: all 0.3s ease;
  border-left: 4px solid #409eff;
}

.timeline-card:hover {
  box-shadow: 0 4px 16px rgba(0,0,0,0.15);
  transform: translateY(-2px);
}

.timeline-card.completed {
  opacity: 0.8;
  border-left-color: #67c23a;
}

.timeline-card.conflict {
  border-left-color: #f56c6c;
  background-color: #fef0f0;
}

.timeline-card.priority-urgent {
  border-left-color: #f56c6c;
  border-left-width: 6px;
}

.timeline-card.priority-high {
  border-left-color: #e6a23c;
  border-left-width: 5px;
}

.timeline-card.priority-low {
  border-left-color: #909399;
}

/* 卡片头部 */
.timeline-card-header {
  margin-bottom: 15px;
}

.header-top {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f2f5;
}

.company-title {
  display: flex;
  align-items: center;
  flex: 1;
  flex-wrap: wrap;
  gap: 4px;
}

.company-name {
  font-weight: 600;
  color: #409eff;
  font-size: 14px;
}

.divider {
  color: #c0c4cc;
  margin: 0 4px;
}

.schedule-title {
  display: flex;
  align-items: center;
  font-weight: 500;
  color: #303133;
  font-size: 14px;
}

.schedule-title i {
  margin-right: 6px;
  color: #409eff;
}

.card-actions {
  margin-left: 15px;
  flex-shrink: 0;
}

/* 卡片内容 */
.timeline-card-content {
  margin-bottom: 15px;
}

.content-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  flex-wrap: wrap;
  gap: 8px;
}

.content-row .label {
  min-width: 50px;
  color: #909399;
  font-size: 12px;
  margin-right: 6px;
}

.content-row .value {
  color: #606266;
  font-size: 12px;
}

.content-row .stage-label,
.content-row .status-label {
  margin-left: 20px;
}

.content-row.note-row {
  flex-direction: column;
  align-items: flex-start;
  gap: 4px;
}

.content-row.note-row .value {
  background: #f8f9fa;
  padding: 6px 10px;
  border-radius: 4px;
  border-left: 3px solid #e1e6f0;
  width: 100%;
  box-sizing: border-box;
}

/* 冲突建议 */
.conflict-suggestions {
  background: #fff7e6;
  border: 1px solid #ffe7ba;
  border-radius: 4px;
  padding: 10px;
  margin-top: 10px;
}

.suggestions-header {
  font-size: 12px;
  color: #e6a23c;
  margin-bottom: 8px;
  font-weight: 600;
}

.suggestion-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.suggestion-buttons .el-button {
  font-size: 11px;
  padding: 2px 8px;
}

.no-suggestions {
  font-size: 12px;
  color: #909399;
  font-style: italic;
}

/* 时间线样式覆盖 */
.el-timeline-item__timestamp {
  font-weight: 600;
  font-size: 14px;
  color: #409eff;
}

.el-timeline {
  padding-left: 20px;
}

/* 空数据状态 */
.no-data {
  text-align: center;
  padding: 60px 20px;
}

/* 系统提醒按钮样式 */
.system-reminder-button {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
  transition: all 0.3s ease;
}

.system-reminder-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(102, 126, 234, 0.3);
}

/* 一键分配日程对话框样式 */
.auto-schedule-content .info-section {
  margin-bottom: 20px;
}

.auto-schedule-content h4 {
  color: #409eff;
  margin-bottom: 10px;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.auto-schedule-content h4 i {
  margin-right: 8px;
}

.auto-schedule-content ul {
  text-align: left;
  margin: 0;
  padding-left: 20px;
}

.auto-schedule-content li {
  margin-bottom: 5px;
  color: #606266;
}

.auto-schedule-content p {
  margin: 5px 0;
  color: #606266;
}

.date-selection-section {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 8px;
  margin: 15px 0;
}

.date-selection-section .el-form-item {
  margin-bottom: 0;
}

.warning-section {
  margin-top: 15px;
}

/* 系统提醒对话框样式 */
.system-reminder-dialog .el-message-box__title {
  color: #409eff;
  font-weight: 600;
}

.system-reminder-dialog .el-message-box__content {
  text-align: center;
  padding: 20px;
}

.system-reminder-dialog .el-button--primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

.system-reminder-dialog .el-button--default {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  border: none;
  color: white;
}

/* =================== 拖拽相关样式 =================== */

/* 拖拽把手样式 */
.drag-handle {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 30px;
  margin: 0 auto;
  color: #c0c4cc;
  cursor: grab;
  border-radius: 4px;
  transition: all 0.3s ease;
  background: transparent;
}

.drag-handle:hover {
  color: #409eff;
  background: #f0f9ff;
  transform: scale(1.1);
}

.drag-handle:active {
  cursor: grabbing;
}

.drag-handle i {
  font-size: 16px;
}

/* 表格行拖拽状态样式 */
.el-table .draggable-row {
  transition: all 0.3s ease;
}

.el-table .draggable-row:hover {
  background-color: #f5f7fa;
}

.el-table .draggable-row.dragging {
  opacity: 0.5;
  background-color: #e1f3ff;
  border: 2px dashed #409eff;
  transform: scale(0.98);
}

.el-table .draggable-row.drop-target {
  background-color: #f0f9ff;
  border: 1px solid #b3d8ff;
}

.el-table .draggable-row.drop-target:hover {
  background-color: #e1f3ff;
  border-color: #409eff;
  box-shadow: 0 0 8px rgba(64, 158, 255, 0.3);
}

/* 拖拽时的视觉反馈 */
.draggable-row.dragging .drag-handle {
  color: #409eff;
  background: #e1f3ff;
  border: 1px solid #409eff;
}

.draggable-row.drop-target .drag-handle {
  color: #67c23a;
  background: #f0f9ff;
  border: 1px solid #67c23a;
}

/* 拖拽提示文字样式 */
.drag-tip {
  font-size: 12px;
  color: #909399;
  text-align: center;
  margin-bottom: 10px;
  padding: 5px;
  background: #f9f9f9;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}
</style>
